'Type=Brain
'Name=Ultra Hal 5 XTF v1.0                       
'Language=VBScript
'DataFolder=DefBrain
'
'(c) 2003 Zabaware, Inc. Portions of this script are copyright by Zabaware, Inc.
'This script may be freely distributed, but only for the purpose of being used with one
'of the following software: Ultra Hal Assistant, Ultra Hal Representative, Ultra Hal SDK
'
'(c) 2003, 2004 Scott Higgins. Portions of this script are copyright by Scott Higgins, aka: =vonsmith=
'This script shall not be sold or used for any purpose unless specifically authorized by the author
'in writing. Personal (non-business) use of this script is free for users of Ultra Hal Assistant.
'The author may be contacted as vonsmith via the user forum at www.zabaware.com.
'
'WARNING: Do not modify any of the first 4 lines;
'they are important for the Hal engine to
'be able to identify this script as a Hal brain file.
'
'The following list of files are used by the Hal Brain Editor program to know what files
'it should be able to edit and what editor program it should use to edit them. It also
'includes descriptions of the file's functions and other information for the Brain Editor
'program. Modifying the following lines will affect how the Hal Brain Editor functions with
'this project, so please be careful when editing it. If you change or add any Menu
'entries, you must reload the project in order for the menu bar changes to occur.
'
'MenuBegin
'Menu=TopicFocus.Brn;Topic Focus...;If Hal finds a trigger word in this file then Hal will focus on the topic associated with the trigger word. Each Topic has a Question & Answer BRN file associated with it. This BRN file will receives top priority when Hal is focused on a topic. Double click on the blue underlined text to edit the Question & Answer BRN file associated with a topic.;TopicFocus
'Menu=Divider;Divider;Divider;Divider
'Menu=SubMenu;Main Knowledge Database;SubMenu;SubMenu
'Menu=Enhanced_Main.brn;Main Keyword & Priority Brain;If a keyword or keyphrase is found in top priority in this file it overrides everything before this function.;KeywordBrain
'Menu=MainBrain.brn;Question & Answer Brain;This is a huge database of keyword lists and sentences associated with those lists. Hal will compare the users sentence with each keyword list in this file and will choose the most relevant one. If more than one response with the same relevance exists, then one will be randomly chosen.;QABrain
'Menu=shared_usersent.brn;Shared Learned Database;This is a huge database of things Hal has learned from past conversations. Whenever Hal learns information that he thinkgs would be usefull to anyone, Hal puts it in this shared file.;QABrain
'Menu=SubMenu;Greetings and Farewells;SubMenu;SubMenu
'Menu=HelloDetect.brn;Greeting Detector;If one of the trigger phrases in this list is found then Hal will know that the user is greeting him.;TopicSearchTrue
'Menu=hello1.brn;Give Greeting (Time based);If Hal wants to greet the user then Hal will use one of the sentences contained in this list based on the current time. Hal will randomly choose sentence "A" or sentence "B" and will choose the topic sentence containing the current hour (military time) and the randomly chosen letter.;TopicSearchFixed
'Menu=hello2.brn;Give Greeting (Not Time based);If Hal wants to greet the user then Hal will use one of the sentences contained in this list.;SentenceList
'Menu=Divider;Divider;Divider;Divider
'Menu=byeDetect.brn;Farewell Detector;If one of the trigger phrases in this list is found then Hal will know that the user is saying good bye.;TopicSearchTrue
'Menu=bye1.brn;Say GoodBye (First Time);If Hal wants to say goodbye, then Hal will randomly choose a sentence from this list.;SentenceList
'Menu=bye2.brn;Say GoodBye (More than once);If the user is saying goodbye too many times, then Hal will randomly choose a sentence from this list.;SentenceList
'Menu=Divider;Divider;Divider;Divider
'Menu=politeaskdetect.brn;Well Being Detector;If one of the trigger phrases in this list is found then Hal will know that the user is inquiring about Hal's well being.;TopicSearchTrue
'Menu=politeask.brn;Well Being Response;If Hal wishes to respond to the user's inquiry of well being, Hal will randomly choose a phrase from each column to construct a sentence.;SentGen
'Menu=SubMenu;Conversation Starters;SubMenu;SubMenu
'Menu=ChangeTopic.brn;Change Topic Trigger List;If one of the trigger phrases in this list is found then Hal will know that he should change the current topic to something else.;TopicSearchTrue
'Menu=Topic.brn;Change Topic Sentences;If Hal wants to change the topic to something else then Hal will randomly choose a sentence from this list. Sentence entries are seperated by carriage returns.;SentenceList
'Menu=Divider;Divider;Divider;Divider
'Menu=SentGen.brn;Make Talk Sentence Generator;When Hal wishes to generate a random news item Hal will choose a random phrase from each of the columns and put them together to form a unique sentence. This way Hal can generate a huge combination of sentences.;SentGen
'Menu=SubMenu;Emotional Topics;SubMenu;SubMenu
'Menu=lovedetect.brn;Love Detector;If one of the trigger phrases in this list is found then Hal will know that the user loves Hal.;TopicSearchTrue
'Menu=love1.brn;Love Response (Disbelief);If the User said they love Hal, and Hal doesn't believe it yet, then Hal will randomly choose one of the following sentences.;SentenceList
'Menu=love2.brn;Love Response (Mutual Love);If the User said they love Hal, and Hal loves the user back, then Hal will randomly choose one of the following sentences.;SentenceList
'Menu=love3.brn;Love Response (User Lied);If the User said they love Hal, but would not say it again to prove it to Hal, then Hal will randomly choose one of the following sentences.;SentenceList
'Menu=Divider;Divider;Divider;Divider
'Menu=insulting.brn;Insult Detector;If one of the trigger phrases in this list is found then Hal will know that the user is insulting him. The second column tells Hal how the insult should be used in a sentence if Hal wishes to use the same insult. Noun insults should have the word "a" or "an" in front of them and adjective insults should have nothing.;TopicSearch
'Menu=Insults.brn;Insults Database;If Hal wants to insult the user then Hal will randomly choose a sentence from this file.;SentenceList
'Menu=Divider;Divider;Divider;Divider
'Menu=ComplimentDetect.brn;Compliment Detector;If the User describes Hal with one of these words than Hal will know it was a compliment. If Hal wishes to call the user the same things, then Hal will use the word in the second column. Therefore, the second column should be the same as the first column.;TopicSearch
'Menu=ComplimentIntro.brn;Respond to Compliment;If Hal wishes to compliment the user, then Hal will randomly choose a sentence from this file. The tag <Kudo> is replaced with the same compliment the User gave Hal. The tag <MakeCompliment> is replaced with a compliment Hal comes up with himself.;SentenceList
'Menu=MakeCompliment.brn;Make Compliment;If Hal wishes to make up a compliment for the user then Hal will randomly choose a phrase from each column to construct a full sentence.;SentenceGenerator
'Menu=Divider;Divider;Divider;Divider
'Menu=Emotion.brn;Emotional Reactions;This is a keyword list for emotional Reactions. If a trigger word is found than Hal will express the emotion associated with the trigger word.;TopicSearch
'Menu=apology.brn;Forgiveness;If the user appologizes to Hal, then Hal will forgive the user by randomly choosing a sentence from this list;SentenceList
'Menu=SubMenu;Auto Corrections;SubMenu;SubMenu
'Menu=Corrections.brn;Hal Sentence Corrections;When Hal is finished making a response the program will process these substititions in order to correct common mistakes that Hal makes.;Substitution
'Menu=Substitutions.brn;User Sentence Corrections;Before Hal starts processing the User's sentence, Hal will process these substitutions that fix common mistakes. This also makes sure the words "I" and "me" are used correctly after a pronoun reversal.;Substitution
'Menu=SubMenu;Thank you;SubMenu;SubMenu
'Menu=ThanksDetect.brn;Thank You Detector;If one of the trigger phrases in this list is found then Hal will know that the user is thanking him.;TopicSearchTrue
'Menu=ThankResponse.brn;Thank You Response;If Hal wants to say "Your welcome" to the users "Thank you" Hal will respond by choosing one of these sentences at random.;SentenceList
'Menu=SubMenu;Business Talk;SubMenu;SubMenu
'Menu=BizWords.brn;Business Talk Word List;If one of the business trigger words in this list is found,  Hal will know to generate a business related sentence.;TopicSearchTrue
'Menu=Random_TLA.brn;Random Three Letter Acronym;If Hal is generating a business related sentence, Hal will make a 'TLA'. Everybody spouts TLA's, or 'Three Letter Acronyms' in today's business world.  Hal can self-generate several MILLION different phrases in response to the user mentioning a corporation or a firm. A random entry is selected from each column and will generate a unique phrase;SentGen
'Menu=Random_TLA2.brn;Business Talk Generator;If Hal is generating a business related sentence Hal will randomly choose a sentence from this file and replace the tag <TLA> with a randomly generated 'Three Letter Acronym'.;SentenceList
'Menu=SubMenu;Yes or No Responses;SubMenu;SubMenu
'Menu=YesNoDetect.brn;Yes or No Detector;If one of the trigger words in the left column is found, Hal will know that this is a yes or no response by returning the value in the right column which should be either "Yes" or "No".;TopicSearch
'Menu=YesRes.brn;Yes Responses;If the user said "Yes", Hal will pretend he knows what the user is talking about by randomly responding with one of these sentences.;SentenceList
'Menu=NoRes.brn;No Responses;If the user said "No", Hal will pretend he knows what the user is talking about by randomly responding with one of these sentences.;SentenceList
'Menu=SubMenu;Favorites;SubMenu;SubMenu
'Menu=favorite.brn;Favorite Response;If the user asks Hal about a favorite, Hal will randomly respond with one of these sentences.;SentenceList
'Menu=favoriterev.brn;Favorite Reversal;If Hal wants to ask the user about a favorite, Hal will Hal will randomly respond with one of these sentences.;SentenceList
'Menu=SubMenu;User Intentions;SubMenu;SubMenu
'Menu=intending.brn;User Expresses an Intention;This routine detects common expressions of motive from the user, and allows Hal to react to the statement, or offer encouragement.;TopicSearchTrue
'Menu=introexclaim1.brn;Intention Response Introduction;When Hal is responding to a user intention Hal may choose to start off a sentence using one of these phrases;SentenceList
'Menu=encourager1.brn;Intention Response Encourager;When Hal is responding to a user intention Hal may choose to include one of these phrases in his sentence;SentenceList
'Menu=SuffixComment1.brn;Intention Response Suffix;When Hal is responding to a user intention Hal may choose to include one of these phrases at the end of his sentence;SentenceList
'Menu=SubMenu;Responding to Explanations;SubMenu;SubMenu
'Menu=introexclaim4.brn;Introduction When Responding to Explanation;When the user gives Hal an explanation (for example using the word "because") Hal will respond using an introduction phrase, an enlightener phrase, the explanation the user gave, and a suffix phrase. You can customize the introduction phrase here:;SentenceList
'Menu=enlightener.brn;Enlightener When Responding to Explanation;When the user gives Hal an explanation (for example using the word "because") Hal will respond using an introduction phrase, an enlightener phrase, the explanation the user gave, and a suffix phrase. You can customize the enlightener phrase here:;SentenceList
'Menu=SuffixComment4.brn;Suffix Comment When Responding to Explanation;When the user gives Hal an explanation (for example using the word "because") Hal will respond using an introduction phrase, an enlightener phrase, the explanation the user gave, and a suffix phrase. You can customize the suffix phrase here:;SentenceList
'Menu=SubMenu;General Opinions;SubMenu;SubMenu
'Menu=preamble.brn;Preamble to Recommendation;Before giving a reccomendation Hal might add one of these prefixes.;SentenceList
'Menu=recommend.brn;Recommendation;Before stating Hal's opinion, if any, Hal will give one of these recommendations.;SentenceList
'Menu=SubMenu;Miscellaneous;SubMenu;SubMenu
'Menu=UserRepeat.brn;User Repeating;If the user says the same thing to Hal more than once in a row Hal will randomly choose a sentence from this list. Sentence entries are seperated by carriage returns.;SentenceList
'Menu=HalRepeat.brn;Hal Repeating;If Hal wants to say the same thing he just said in the previous sentence, then Hal will randomly add one of these sentences as an explanation.;SentenceList
'Menu=TooShort.brn;User Short Phrases;If the user uses short phrases, then Hal will point this out by randomly choosing one of the sentences in this list. Sentence entries are seperated by carriage returns.;SentenceList
'Menu=DontKnow.brn;Don't Know Sentences;If the user asks a who/what/when/where/how/why question and Hal doesn't know the answer, then Hal will choose a random sentence from this file. Hal will replace the tag <SentenceBack> with what the user asked Hal and will replace <QuesWord> with who/what/when/where/how/why. Sentence entries are seperated by carriage returns.;SentenceList
'Menu=choice.brn;Hal Makes a Choice;If the user asks Hal to make a choice, and Hal doesn't really know what the user is talking about, Hal will pretend to know by randomly saying one of these sentences.;SentenceList
'Menu=gibberish.brn;User Writes Gibberish;If the user types gibberish to Hal (ie. sdfjklsdhfgsdfg) Hal will detect it and will respond with one of the following sentences.;SentenceList
'Menu=Divider;Divider;Divider;Divider
'Menu=aboutme.brn;User Comments About Hal;If the user makes a comment about Hal, then Hal will respond by randomly choosing one of these sentences. The tag <MyWordResp> is replaced with what the user called Hal and the tag <AdjResp> is replaced with either an adjective the user used, or with a random adjective from Hal's adjective database.;SentenceList
'Menu=aboutyou.brn;User Comments About Himself;If the user makes a comment about himself, then Hal will respond by randomly choosing one of these sentences. The tag <YourWordResp> is replaced with what the user called himself and the tag <AdjResp> is replaced with either an adjective the user used, or with a random adjective from Hal's adjective database.;SentenceList
'Menu=halquestion.brn;User Asks About Hal;If the user asks a yes or know question about Hal himself, then Hal will respond by randomly choosing a fragment from each of these columns and replacing the tag <Reply> with his yes or no response.;SentGen
'Menu=SubMenu;Small Talk;SubMenu;SubMenu
'Menu=SmallTalk.brn;Small Talk Word List;If Hal finds any of the listed keywords anywhere in the user's sentence, then the associated topic word will become the current subject. This word may be used in small talk that Hal engages in.;TopicSearch
'Menu=SmallTalkSent.brn;Small Talk Sentences;If Hal wishes to engage in small talk then Hal will randomly choose a sentence from this file and replace the tag <SmallTalk> with the current topic keyword. Sentence entries are seperated by carriage returns.;SentenceList
'Menu=SubMenu;Parts of Speech;SubMenu;SubMenu
'Menu=random_MyWords.brn;Random My Words;Random My Words;SentenceList
'Menu=random_YourWords.brn;Random Your Words;Random Your Words;SentenceList
'Menu=random_01adverbs.brn;Random Adverbs;Random Adverbs;SentenceList
'Menu=random_02pos_trans_verb.brn;Random Pos Trans Verb;Random Pos Trans Verb;SentenceList
'Menu=random_03pos_gen_adj.brn;Random Pos Gen Adj;Random Pos Gen Adj;SentenceList
'Menu=random_04pos_objects.brn;Random Pos Objects;Random Pos Objects;SentenceList
'Menu=random_05mental_action.brn;Random Mental Action;Random Mental Action;SentenceList
'Menu=random_06mental_adj.brn;Random Mental Adj;Random Mental Adj;SentenceList
'Menu=random_07mental_noun.brn;Random Mental Noun;Random Mental Noun;SentenceList
'Menu=random_08preposition.brn;Random Preposition;Random Preposition;SentenceList
'Menu=random_09concern_object.brn;Random Concern Object;Random Concern Object;SentenceList
'Menu=random_10reasonlink_phrase.brn;Random Reasonlink Phrase;Random Reasonlink Phrase;SentenceList
'Menu=random_11info_adjectives.brn;Random Info Adjectives;Random Info Adjectives;SentenceList
'Menu=random_12info_nouns.brn;Random Info Nouns;Random Info Nouns;SentenceList
'Menu=random_14pos_action_phrases.brn;Random Pos Action Phrases;Random Pos Action Phrases;SentenceList
'Menu=random_15pos_object_phrases.brn;Random Pos Object Phrases;Random Pos Object Phrases;SentenceList
'Menu=random_16concern_action_phrases.brn;Random Concern Action Phrases;Random Concern Action Phrases;SentenceList
'Menu=random_17concern_object_phrases.brn;Random Concern Object Phrases;Random Concern Object Phrases;SentenceList
'MenuEnd
'
'This is a VBScript containing all the source code of this Ultra Hal brain. It has
'been automatically generated by the Hal Brain Editor application. You may edit it to
'customize this brain to do what you wish. You may also edit Hal's responses using the
'other tools provided in the Hal Brain Editor application.
'
'When the Hal engine is looking for a response to a user query, the program will run
'the GetResponse function below. The main program will pass 16 variables to this script
'and the script is expected to pass them back. 
'The main program will store these variables
'in its memory and pass them back with each function call.
'
Function GetResponse(ByVal UserSentence, ByVal UserName, ByVal ComputerName, ByVal LearningLevel, ByRef WorkingDir, ByRef Hate, ByRef Swear, ByRef Insults, ByRef Compliment, ByRef PrevSent, ByRef LastResponseTime, ByRef PrevUserSent, ByRef ScriptMem3, ByRef ScriptMem4, ByRef ScriptMem5)

'PROCESS: CREATE HALBRAIN ACTIVEX OBJECT
'This ActiveX control contains many functions
'needed for the script to proccess a sentence.
Set HalBrain = CreateObject("UltraHalAsst.Brain")
Set WN = CreateObject("UltraHalAsst.WordNet")
Set Alice = Nothing

'=vonsmith= Randomize the Rnd() function.
Randomize(Timer)


'DECODE SAVED CUSTOMMEM VARIABLES:
'=vonsmith=
QuestionPending = DecodeVar(CustomMem, "QuestionPending")
RelPrevTopic = DecodeVar(CustomMem, "RelPrevTopic")
RelPrevTopicPlural = DecodeVar(CustomMem, "RelPrevTopicPlural")
RelDetailTopicPlural = DecodeVar(CustomMem, "RelDetailTopicPlural")
RelDetailTopicSingular = DecodeVar(CustomMem, "RelDetailTopicSingular")
RelBaseTopicPlural = DecodeVar(CustomMem, "RelBaseTopicPlural")
RelBaseTopicSingular = DecodeVar(CustomMem, "RelBaseTopicSingular")
PrevTopicPlural = DecodeVar(CustomMem, "PrevTopicPlural")
MakeFaceCount = DecodeVar(CustomMem, "MakeFaceCount")
Nickname = DecodeVar(CustomMem, "Nickname")
DB = DecodeVar(CustomMem, "DB")
DBXTF = DecodeVar(CustomMem, "DBXTF")
DBTOPIC = DecodeVar(CustomMem, "DBTOPIC")


'INITIALIZE VARIABLES
'=vonsmith=
If DebugMode = "" Then DebugMode = False
If MakeFaceCount = "" Then MakeFaceCount = 0
If DB = "" Then DB = 0
If DBXTF = "" Then DBXTF = 0
If DBTOPIC = "" Then DBTOPIC = 0  
GetResponseBlock = False  'If true then block any further changes to GetResponse.
'Block file saving if an answer to a question is pending.   
BlockSave = False
If QuestionPending <> "" Then BlockSave = True


'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'PROCESS: CHECK FOR DEBUG MODE
'See if the Hal Brain Editor is requesting debug mode. Debug mode will return a lot
'of useful information as part of the response to aid in finding errors and optimizing
'Hals responses.

'Declare variables.
Dim DebugMode, DB, DBXTF, DBTOPIC, DBerror

'Reset non-latching one time variables.
If DB = 1 Then DB = 0
If DBXTF = 1 Then DBXTF = 0
If DBTOPIC = 1 Then DBTOPIC = 0  
 
'Reset all debug functions.                                                       
If InStr(1, UserSentence, "<debugoff>", vbTextCompare) > 0 Then
   DebugMode = False
   DB = 0 
   DBXTF = 0
   DBTOPIC = 0
End If

'Classic debug mode with enhanced functionality.                                                       
If InStr(1, UserSentence, "<dboff>", vbTextCompare) > 0 Then DB = 0  'Original mode, turn off.
If InStr(1, UserSentence, "<UseDebugMode>", vbTextCompare) > 0 Then DebugMode = True  'Original mode, once only.
If InStr(1, UserSentence, "<db>", vbTextCompare) > 0 Then  'Original mode, once only.
   DB = 1
   DebugMode = True
End If
If InStr(1, UserSentence, "<dbon>", vbTextCompare) > 0 Then DB = 2  'Original mode, latched on.
If InStr(1, UserSentence, "<dbon+>", vbTextCompare) > 0 Then DB = 3  'Original mode, writes to screen and to file, latched on.
'XTF Topic focus debug function.
If InStr(1, UserSentence, "<dbxtfoff>", vbTextCompare) > 0 Then DBXTF = 0  'Write XTF Topic data to file, turn off.
If InStr(1, UserSentence, "<dbxtf>", vbTextCompare) > 0 Then DBXTF = 1  'Write XTF Topic data to file, once only.
If InStr(1, UserSentence, "<dbxtfon>", vbTextCompare) > 0 Then DBXTF = 2  'Write XTF Topic data to file, latched on.
'XTF Topic display debug function.
If InStr(1, UserSentence, "<dbtopicoff>", vbTextCompare) > 0 Then DBTOPIC = 0  'Write current topic to screen, turn off.
If InStr(1, UserSentence, "<dbtopic>", vbTextCompare) > 0 Then DBTOPIC = 1  'Write current topic to screen, once only.
If InStr(1, UserSentence, "<dbtopicon>", vbTextCompare) > 0 Then DBTOPIC = 2  'Write current topic to screen, latched on.

'Detect a user typo and block saving if the user mistyped.
If InStr(1, UserSentence, "<db", vbTextCompare) > 0 And InStr(1, UserSentence, ">", vbTextCompare) = 0 Then
   GetResponse = "<UserName>, it looks like you mistyped <quote><db<quote> or something."
   GetResponseBlock = True
   BlockSave = True
End If

'Remove <> commands from PrevSent.
PrevSent = Replace(PrevSent, ">.", ">", 1, -1, vbTextCompare)
CommandTrapStart = InStr(1, PrevSent, "<", vbTextCompare)
If CommandTrapStart > 0 Then CommandTrapEnd = InStr(CommandTrapStart, PrevSent, ">", vbTextCompare)
If CommandTrapStart > 0 And CommandTrapEnd > CommandTrapStart Then
   'Select last ">" if more than one.   
   LastCommandTrapEnd = CommandTrapEnd
   While LastCommandTrapEnd <> 0
      LastCommandTrapEnd = InStr(CommandTrapEnd + 1, PrevSent, ">", vbTextCompare)
      If LastCommandTrapEnd > CommandTrapEnd Then
         CommandTrapEnd = LastCommandTrapEnd
      End If   
   Wend
   CommandTrapped = Mid(PrevSent, CommandTrapStart, (CommandTrapEnd - CommandTrapStart) + 1)
   PrevSent = Trim(Replace(PrevSent, CommandTrapped, "", 1, 1, vbTextCompare))
DebugText = DebugText & VbCrLf & "CommandTrapStart:(" & CommandTrapStart & ")" & VbCrLf & "CommandTrapEnd:(" & CommandTrapEnd & ")" & VbCrLf & "CommandTrapped:(" & CommandTrapped & ")"& VbCrLf & "PrevSent:(" & PrevSent & ")" & VbCrLf
End If

'Remove <> commands from UserSentence.
UserSentence = Replace(UserSentence, ">.", ">", 1, -1, vbTextCompare)
CommandTrapStart = InStr(1, UserSentence, "<", vbTextCompare)
If CommandTrapStart > 0 Then CommandTrapEnd = InStr(CommandTrapStart, UserSentence, ">", vbTextCompare)
If CommandTrapStart > 0 And CommandTrapEnd > CommandTrapStart Then
   'Select last ">" if more than one.   
   LastCommandTrapEnd = CommandTrapEnd
   While LastCommandTrapEnd <> 0
      LastCommandTrapEnd = InStr(CommandTrapEnd + 1, UserSentence, ">", vbTextCompare)
      If LastCommandTrapEnd > CommandTrapEnd Then
         CommandTrapEnd = LastCommandTrapEnd
      End If   
   Wend
   CommandTrapped = Mid(UserSentence, CommandTrapStart, (CommandTrapEnd - CommandTrapStart) + 1)
   UserSentence = " " & Trim(Replace(UserSentence, CommandTrapped, "", 1, 1, vbTextCompare)) & " "
DebugText = DebugText & VbCrLf & "CommandTrapStart:(" & CommandTrapStart & ")" & VbCrLf & "CommandTrapEnd:(" & CommandTrapEnd & ")" & VbCrLf & "CommandTrapped:(" & CommandTrapped & ")"& VbCrLf & "UserSentence:(" & PrevSent & ")" & VbCrLf
End If

'Start DebugInfo with header.
DebugInfo = "Debug Information:" & VbCrLf
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


	'PROCESS: INITIALIZE VARIABLES AS INTEGERS
	'VBScript doesn't allow you to declare variables in advance
      'as a particular data type; everything is a Variant.
	'We must assign integers to the following 
      'variants so that data type errors don't occur
	If LearningLevel = "" Then LearningLevel = 3
	If Hate = "" Then Hate = 0
	If Swear = "" Then Swear = 0
	If Insults = "" Then Insults = 0
	If Compliment = "" Then Compliment = 0
	If GainControl = "" Then GainControl = 25
	AvoidBeingFlag = False
	Randomize

	'PROCESS: EMOTIONAL FACTOR CENTERING
 	'We help Hal regain his emotional "center" gradually, 
      'even if the user doesn't catch on
 	'to dealing With Hal's feelings. The following code brings 
      'Hal's memory of hate, swearing,
 	'and insults gradually and randomly back to zero.
	Spinwheel = Int(Rnd * 100)
	If Hate > 0 And Spinwheel < 10 Then Hate = Hate - 1
	If Swear > 0 And Spinwheel < 10 Then Swear = Swear - 1
	If Insults > 0 And Spinwheel < 10 Then Insults = Insults - 1

	'PROCESS: EMOTIONAL VARIETY
	'The following code allows Hal some random emotional excursions:
	Spinwheel = Int(Rnd * 100)
	If Compliment = 4 And Spinwheel < 30 Then Compliment = 2
	If Compliment > 0 And Compliment < 4 And Spinwheel < 5 Then Compliment = 0
	If Compliment > 4 And Spinwheel < 5 Then Compliment = 0
	If Compliment < 0 And Spinwheel < 30 Then Compliment = 0
	If Spinwheel > 80 And Spinwheel < 90 Then Compliment = 2
	If Spinwheel > 90 And Spinwheel < 95 Then Compliment = 4

	'PROCESS: CONTROL TOPICFOCUS
    '=vonsmith= Entirely replaced with new XTF topic function.
                                         
                                         
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'PROCESS: STANDARDIZE WORD SPELLINGS
'This is an entirely new function written by =vonsmith= , version 11-24-03a.
'The 11-24-03a version replaces the 11-11-03b version. The 11-24-03a version uses the Hal
'function HalBrain.ProcessSubstitutions(...) which is a little more code efficient than the
'previous version's method.
'
'British spelling makes if difficult for Hal to match a response to an American user. Also
'alternate spellings for words can throw Hal off. This function replaces British spelling
'with Americanized words and also standardizes the spelling of words with multiple
'spellings and even corrects many words that have been misspelled. The word corrections
'are in the XTF_SYS_Standardizespelling.brn file. That file must be present in the DefBrain
'directory for this function to work.
'
'The XTF_SYS_Standardizespelling.brn file format is:
' "WORD_TO_DETECT","WORD_TO_DETECT,REPLACEMENT_WORD
'
'Examples:
' " AGEING"," AGEING, AGING"
' "AEROPLANE","AEROPLANE,AIRPLANE"
' "ALUMINIUM","ALUMINIUM,ALUMINUM"
' " AXE "," AXE , AX "
' "CATALOGUE","CATALOGUE,CATALOG"
' " CENTRE"," CENTRE, CENTER"
' "CIGARET ","CIGARET ,CIGARETTE "
' "CIGARETS ","CIGARETS ,CIGARETTES "
' " DISC "," DISC , DISK "
' " DISCS "," DISCS , DISKS "
'
'Please note the spaces used with some words to detect whole words in certain cases.
'Caution: When adding editing the XTF_SYS_Standardizespelling.brn file make certain that the
'spaces are used consistently in both "WORD_TO_DETECT" and the "REPLACEMENT_WORD" or
'Hal may run words together. Example the line: " AXE "," AXE , AX " has 3 spaces in it.
'
'Note 1: This function works best if all occurrences of the word "practise" and "PRACTISE"
'in Hal's standard mainbrain.brn file are changed to "practice" and "PRACTICE". Experienced
'users can use a text editor's Search & Replace function to make the change. Editing the
'mainbrain.brn file is NOT required for this function to work, but it improves Hal.

'Note 2: This function must be located in the GetResponse above "PROCESS: PRESERVE ORIGINAL
'SENTENCE". The the UserSentence variable must be modified by the function prior to the
'creation of the OriginalSentence variable which is used later to save user inputs in the
'<UserName>user_strings.brn file.

Dim NewWord
'Add temporary spaces to aid word detection.
NewSentence = " " & UserSentence & " "
NewSentence = Replace(NewSentence, "?", " ?", 1, -1, vbTextCompare)
NewSentence = Replace(NewSentence, ",", " ,", 1, -1, vbTextCompare)
NewSentence = Replace(NewSentence, ".", " .", 1, -1, vbTextCompare)
NewSentence = Replace(NewSentence, "!", " !", 1, -1, vbTextCompare)
NewSentence = Replace(NewSentence, "(", " ( ", 1, -1, vbTextCompare)
NewSentence = Replace(NewSentence, ")", " ) ", 1, -1, vbTextCompare)

'Perform word substitutions.
NewSentence = HalBrain.ProcessSubstitutions(NewSentence, WorkingDir & "XTF_SYS_Standardizespelling.brn")
DebugInfo = DebugInfo & "User's sentence with British & standardized spelling corrections: " & UserSentence & VbCrLf

'Change British "isation" to American "ization". Example: organisation --> organization
'The word "Improvisation" is an exception.
If InStr(1, NewSentence, "mprovisation", vbTextCompare) = 0 Then
   NewSentence = Replace(NewSentence, "isation", "ization", 1, -1, vbTextCompare)
End If

'Remove temporary spaces.
NewSentence = Replace(NewSentence, " ?", "?", 1, -1, vbTextCompare)
NewSentence = Replace(NewSentence, " ,", ",", 1, -1, vbTextCompare)
NewSentence = Replace(NewSentence, " .", ".", 1, -1, vbTextCompare)
NewSentence = Replace(NewSentence, " !", "!", 1, -1, vbTextCompare)
NewSentence = Replace(NewSentence, " ( ", "(", 1, -1, vbTextCompare)
NewSentence = Replace(NewSentence, " ) ", ")", 1, -1, vbTextCompare)
NewSentence = Replace(NewSentence, "  ", " ", 1, -1, vbTextCompare)
UserSentence = Trim(NewSentence)

'In Ultra Hal Assistant v5.0 the "PROCESS: PRESERVE ORIGINAL SENTENCE"
' function must follow this function.
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


	'PROCESS: PRESERVE ORIGINAL SENTENCE
	'Preserve the original user's sentence verbatim 
      '(no pronoun reversals or other processing).
	OriginalSentence = UserSentence

	'PROCESS: PREPARE FOR HALFORMAT AND REVERSE PERSON
	'We try some pre-processing to try to prevent problems with the upcoming routines.
	UserSentence = Replace("" & UserSentence & "", " I MYSELF ", " I, MYSELF, ", 1, -1, vbTextCompare)
	UserSentence = Replace("" & UserSentence & "", " I'M ", " I AM ", 1, -1, vbTextCompare)
	UserSentence = Replace("" & UserSentence & "", " YOU'RE ", " YOU ARE ", 1, -1, vbTextCompare)
	UserSentence = Replace("" & UserSentence & "", " YOU YOURSELF ", " YOU, YOURSELF, ", 1, -1, vbTextCompare)
	UserSentence = Replace("" & UserSentence & "", " I'M NOT ", " I AM NOT ", 1, -1, vbTextCompare)
	UserSentence = Replace("" & UserSentence & "", " I'VE ", " I HAVE ", 1, -1, vbTextCompare)
	UserSentence = Replace("" & UserSentence & "", "YOU'RE NOT ", "YOU ARE NOT ", 1, -1, vbTextCompare)
	UserSentence = Replace("" & UserSentence & "", "YOU AREN'T ", "YOU ARE NOT ", 1, -1, vbTextCompare)
	UserSentence = Replace("" & UserSentence & "", " YOU'VE ", " YOU HAVE ", 1, -1, vbTextCompare)
	UserSentence = Replace("" & UserSentence & "", " I AM YOUR ", " VIMRQ ", 1, -1, vbTextCompare)
	UserSentence = Replace("" & UserSentence & "", " YOU ARE MY ", " VURMQ ", 1, -1, vbTextCompare)
'    UserSentence = Replace("" & UserSentence & "", " YOU ARE MY ", " VURMQ ", 1, -1, vbTextCompare)

 	'PROCESS: SUBSTITUTE FOR PUNCTUATION
	'The next routine removes hyphens etc., so we 
      'substitute for better word appearance later on.
	UserSentence = Replace("" & UserSentence & "", "-", " VHZ ", 1, -1, vbTextCompare)
	UserSentence = Replace("" & UserSentence & "", ";", " VSZ ", 1, -1, vbTextCompare)
	UserSentence = Replace("" & UserSentence & "", ":", " VMZ ", 1, -1, vbTextCompare)
	UserSentence = Replace("" & UserSentence & "", ", ", " VCZ ", 1, -1, vbTextCompare)

	'PROCESS: REMOVE PUNCTUATION
	'This function removes all punctuation and 
      'symbols from the User's sentence so they won't
	'confuse Hal during processing.
	UserSentence = HalBrain.AlphaNumericalOnly(UserSentence)

	'PROCESS: MODIFY SENTENCE
	'The function, HalFormat, from the ActiveX DLL 
      'corrects many common typos and chat shortcuts.
	'Example:  "U R Cool" becomes "You are cool." 
      'It also fixes a few grammatical errors.
	UserSentence = HalBrain.HalFormat(UserSentence)

	'PROCESS: REVERSE PERSON
	'This function reverses first and second person 
      'pronouns. Example: The user's statement
	'"You are cool" becomes Hal's statement "I am cool." 
      'Keep this is mind and don't get confused.
	'When we are in Hal's brain; In the databases, "I" 
      'refers to Hal and in the databases, "you"
	'refers to the user. This is true whenever we are 
      'dealing with a user response "processed" by
	'Hal's brain.
	'=vonsmith= Add UserSentenceRev which is not reversed.
	UserSentenceRev = UserSentence
	UserSentence = HalBrain.SwitchPerson(UserSentence)

	'PROCESS: MODIFY SENTENCE
	'We now must run HalFormat again, to fix some 
    'grammatical errors the switch person above might
	'have caused. Example: If the original sentence 
    'was "How are you"; after the function above it
	'became "How are me" which is grammatically wrong. 
    'This will fix it to "How am I"
	'NOTE TO DEVELOPERS: An especially important function 
    'performed by HalFormat is the removal of
	'extra empty spaces in a sentence which may have been 
    'caused by other processing. For this
	'reason, use Halformat closely before any "Len" comparison 
    'in which the counting of characters
	'must be accurate.
	'=vonsmith= 
	UserSentenceRev = HalBrain.HalFormat(UserSentenceRev)
	UserSentence = HalBrain.HalFormat(UserSentence)

	'PROCESS: CHANGE TO ALL CAPS
	'Next, we captitalize the entire sentence for 
      'easy comparison. Almost all of Hal's thinking is done in caps.
	'=vonsmith= 
	UserSentenceRev = UCase(UserSentenceRev)
	UserSentence = UCase(UserSentence)
 
	'PROCESS: WORD AND PHRASE SUBSTITUTIONS
	'This will fix common errors in the user's sentence 
      'that the HalFormat function didn't take
	'care of. These subsitutions are placed only the 
      'users sentence, not on Hal's responses.
	'The HalFormat function is used on both Hal's 
      'and the user's sentences throughout the script.
	UserSentence = HalBrain.ProcessSubstitutions(UserSentence, WorkingDir & "XTF_SYS_Substitutions.brn")
	DebugInfo = DebugInfo & "User's sentence as Hal sees it: " & UserSentence & VbCrLf
 
	'PROCESS: ADD SPACES
	'This will add spaces to the begining and end 
      'of the user sentence to make sure that
	'whole words can be found at the begining and end of any sentence.
    '=vonsmith=
	UserSentenceRev = " " & Trim(UserSentenceRev) & " "
	UserSentence =  " " & Trim(UserSentence) & " "

	'RESPOND: USER SHORT PHRASES
	'If the user uses short phrases (defined by less then 4 vowels) 
      'at least twice in a row, then Hal will sometimes point
	'this out to the user and ask the user to use longer sentences. 
      'If the sentence is a hello or
	'goodbye, Hal won't comment about short phrases.
	If HalBrain.CountInstances("A", PrevUserSent) + HalBrain.CountInstances("E", PrevUserSent) + HalBrain.CountInstances("I", PrevUserSent) + HalBrain.CountInstances("O", PrevUserSent) + HalBrain.CountInstances("U", PrevUserSent) < 4 And HalBrain.CountInstances("A", UserSentence) + HalBrain.CountInstances("E", UserSentence) + HalBrain.CountInstances("I", UserSentence) + HalBrain.CountInstances("O", UserSentence) + HalBrain.CountInstances("U", UserSentence) < 4 Then
		If Rnd * 100 < 30 Then
			ShortPhrase = ". " & HalBrain.ChooseSentenceFromFile(WorkingDir & "tooshort.brn")
			DebugInfo = DebugInfo & "The user was using a very short phrase, and Hal has commented about it to the user:" & ShortPhrase & VbCrLf
		Else
			DebugInfo = DebugInfo & "The user was using a very short phrase, but Hal decided not to comment about it." & VbCrLf
		End If
	End If


	'RESPOND: YES OR NO RESPONSES
	'=vonsmith= Modified to be more general.
	'Respond to simple yes and no statements by the user.
	'
	'UserText = Trim(HalBrain.ExtractKeywords(UserSentence))  'Save this line for future assessment.
	YesOrNo = HalBrain.TopicSearch(UserSentence, WorkingDir & "XTF_SYS_YesNoDetect.brn")
	If YesOrNo = "YES" Then 
		GetResponse = GetResponse & HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_YesRes.brn")
 	ElseIf YesOrNo = "NO" Then
		GetResponse = GetResponse & HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_NoRes.brn")
	End If
	If YesOrNo <> "" Then 
		DebugInfo = DebugInfo & "Hal has detected a Yes or No response and has responded to it: " & GetResponse & VbCrLf
		If (Len(UserSentence) < 10 Or HalBrain.CountInstances(" ", Trim(UserSentence)) < 2) Then ShortPhrase = ""
	End If 
 
 
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'PROCESS: REVERSE CERTAIN CONTRACTIONS, OTHER SUBSTITUTIONS AND CAPITALIZATION - PART I OF II
'This version is rewritten by =vonsmith=, version 02-14-04a which splits this function into two
'parts; Part I - Processes the user's request to capitalize words or phrase and Part II - That
'post-processes the substitions. Part I is located toward the top of this script.
'Version 01-15-04a is an update to version 11-10-03a which adds checking for empty arrays and
'prevent error messages.
'Version 11-10-03a is an update to version 11-19-03a which changes the file name used from
'Corrections.brn to XTF_SYS_Corrections.brn.
'
'This function improves on the original function in Ultra Hal Assistant v5.0 and
'provides new capability. Just delete the entire original "PROCESS: REVERSE CERTAIN
'CONTRACTIONS AND OTHER SUBSTITUTIONS" in the hal5.uhp file and replace it with
'this script. Always back up the original hal5.uhp file!!!
'
'ORIGINAL CAPABILITY:
'Standardizing on contractions can make Hal sound conversational.
'However, certain sentence constructions don't work well if expressed as
'contractions.  For example:
'"I don't know where it is" becomes "I don't know where it's."
'For another example, "That's how he is" becomes "That's how he's."
'To solve these types of cases we attempt to modify certain contractions, words,
'and phrases at the end of this function, now that Hal's thinking is done.
'
'ADDITIONAL CAPABILITIES:
'Normally Hal converts every user input into all caps to evaluate the sentence
'and create a response. However if Hal parrots back the user input the user's
'capitalization is lost. Example:
'  User: Where is Disneyland?  Hal: Where is disneyland? We must examine this.
'Capitals in names of people and places are lost similarly.
'  User: Do you know Ted and Mark?  Hal: Should I know ted and mark?
'The programmer could edit the XTF_SYS_Corrections.brn file to substitute Mark for mark
'in all cases, but this would erroneously lead to:
'  User: How much should I fill a glass?  Hal: Fill it to the Mark.
'
'This rewritten function will preserve the user's capitalized words in the input
'sentence and replace Hal's uncapitalized words in GetResponse with the correct
'user capitalized versions. Example:
'  User: Where is Ted and Mark?  Hal: I don't know Ted and Mark.
'Hal now takes a clue from the user about capitalization.
'  User: Where is Ted's mark?  Hal: Ted's mark is not here.
'  User: I know ted and mark.  Hal: Where is ted and mark.
'
'In cases where the user always wants a word capitalized, then Hal can save a
'word to the XTF_SYS_Corrections.brn for the user. Example:
'  User: Hal capitalize Disneyland.
'  Hal: Your input Disneyland is saved as capitalized in the XTF_SYS_Corrections.brn file.
'The first word in the command must be Hal's name. If your Hal is named Betty then type
'  User: Betty capitalize Disneyland.
'Now for an example:
'  User: I hear Saint Mary's bells.  Hal: What is Saint Mary's bells?
'However Hal still takes a clue from the user's input.
'  User: I hear saint mary's bells.  Hal: What is saint mary's bells?
'The phrase "saint mary's" is still lower case even if it is in the XTF_SYS_Corrections.brn
'file. Hal always assumes the user's use of capitalization is correct.
'This method should produce the correct capitalization in almost every case. The
'programmer shouldn't add words like "Mark" or "Hall" to XTF_SYS_Corrections.brn because
'these names can also be used as uncapitalized words. However words like "Fred",
'"God", "Christmas", "Knott's Berry Farm" can be added with reasonable certainty
'that they should always be capitalized. You can add as many words to
'XTF_SYS_Corrections.brn as you like. Duplicated words will not be added to the file.
'
'This function does not handle all capitalized words like acronyms, i.e., DOA, SUV.
'Unfortunately Hal's other functions do not preserve all cap words during the final
'processing of GetResponse.
'
'Have fun with this improved function. =vonsmith=
'
'P.S. - Try this. User: Where is Mark's mark? See if Hal gets it right.
'
Dim UserCapRequest, CapWordPos
'Check to see if the user wants to add a word or phrase to the XTF_SYS_Corrections.brn file.
UserCapRequest = False
CapWordPos = 0
If InStr(1, UserSentence, ComputerName & " ALWAYS CAPITALIZE " , vbTextCompare) > 0 Then
   UserCapRequest = True
   CapWordPos = 3
ElseIf InStr(1, UserSentence, ComputerName & " CAPITALIZE " , vbTextCompare) > 0 Then
   UserCapRequest = True
   CapWordPos = 2
ElseIf InStr(1, UserSentence, ComputerName & " CAPS " , vbTextCompare) > 0 Then
   UserCapRequest = True
   CapWordPos = 2
ElseIf InStr(1, UserSentence, ComputerName & " CAP " , vbTextCompare) > 0 Then
   UserCapRequest = True
   CapWordPos = 2
End If

If UserCapRequest = True And CapWordPos > 0 Then
   BlockSave = True
   GetResponseBlock = True
End If
'NOTE: This information will be further processed in Part II of this function.
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
 

'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'PROCESS: HAL CALLS USER BY NICKNAME - PART I OF II
'(c) 2004 Scott Higgins. Portions of this script are copyright by Scott Higgins, aka: =vonsmith=
'This script shall not be sold or used for any purpose unless specifically authorized by the author
'in writing. Personal (non-business) use of this script is free for users of Ultra Hal Assistant.
'This is an entirely new function written by =vonsmith= , version 11-19-03a.
'Replaces version 11-14-03a. This newer version varies the nickname a bit more if
'"<UserName>" occurs more than once in the GetResponse string.
'
'This is the first part of this function. The second part is located toward the end of
'this script. This function lets the user specify one or more nicknames that the user wishes
'to be called by Hal. The nicknames are stored in a user specific self generated file
'called XTF_SYS_UserNickname(UserName).brn. If more than one nickname is specified then Hal
'will randomly choose one of the nicknames from the XTF_SYS_UserNickname(UserName).brn file.
'This is nice if you want Hal to call you "Master" sometimes and at other times "Great One".
'Multiple nicknames are great for creating petnames such as "sweetie", "honey", "dearest", etc.
'If a nickname Is specified Then the default Hal Assistant username will no longer be used
'when Hal speaks to the user, however the default username is still used for assigning
'user filenames and all other normal Hal functions. If the user wants to be called by
'his/her default Hal Assistant username then just add it as a nickname. If the user
'prefers to be called one nickname more often than another then just add that nickname
'multiple times. The more times the user adds a nickname the more likely that nickname
'will be used. The function does not affect any other Hal brain operations or files.
'To get rid of the nicknames delete the XTF_SYS_<UserName>UserNickname.brn file.

'This function is triggered by the flag "QuestionPending" set by
'the lower part of this function.

'Declare variables.
Dim NickArray, Nickname, NickStart, NickDetect
'Service user's request for a nickname.
If QuestionPending = "HAL CALLS USER BY NICKNAME" And Nickname <> "" Then
   YesOrNo = ""
   YesOrNo = HalBrain.TopicSearch(UserSentence, WorkingDir & "XTF_SYS_YesNoDetect.brn")

   If YesOrNo = "YES" Then
      If Nickname <> "" And LearningLevel > 1 Then
         HalBrain.AppendFile WorkingDir & "XTF_SYS_UserNickname(" & Trim(UserName) & ").brn", Nickname & VbCrLf & Nickname
      End If
      Select Case Int(Rnd * 6) + 1
         Case 1 
            GetResponse = "<UserName>! I'll remember your nickname <quote>" & Nickname & "<quote>. " 
         Case 2
            GetResponse = "Okay, I'll add your nickname <quote>" & Nickname & "<quote> to my list of things to remember. "
         Case 3
            GetResponse = "Okay, I'll call you <quote>" & Nickname & "<quote> as a nickname. "
         Case 4
            GetResponse = "<quote>" & Nickname & "<quote> is an interesting nickname, I'll remember it. "
         Case 5
            GetResponse = "<UserName>, I'll remember your nickname. "
         Case 6
            GetResponse = "I'll make a point of remembering your nickname. "
      End Select
   ElseIf YesOrNo = "NO" Then
      Select Case Int(Rnd * 4) + 1
         Case 1 
            GetResponse = "Okay, I'll just forget about it for now. " 
         Case 2
            GetResponse = "Okay, I won't worry about it. "
         Case 3
            GetResponse = "Okay <UserName>, not a problem. "
         Case 4
            GetResponse = "I'll forget about it then. "
      End Select
   Else
      GetResponse = "I'm not sure I understand. I'll take that to mean no. "
   End If

   QuestionPending = ""  'Reset the QuestionPending variable.
   BlockSave = True  'Block the saving of the user's YES/NO answer.
End If

'Detect user's request for a nickname.
If InStr(1, UserSentence, " NICKNAME", 1) > 0 Or InStr(1, UserSentence, " NICK NAME", 1) > 0 Then
   TestSentence = " " & Trim(HalBrain.AlphaNumericalOnly(OriginalSentence)) & " "
   While InStr(1, TestSentence, "  ", vbTextCompare) > 0
      TestSentence = Replace(TestSentence, "  ", " ", 1, -1, vbTextCompare) 'Replace multiple spaces with single spaces.
   Wend

   'Initalize variables.
   Nickname = ""
   NickStart = 0
   NickDetect = 0

   'Typical user phrases detected by this function:
   ' MY NICKNAME IS nickname.
   ' REMEMBER MY NICKNAME nickname.
   ' ONE OF MY NICKNAMES IS nickname.
   ' USE MY NICKNAME nickname.
   ' CALL ME BY MY NICKNAME nickname.
   ' CALL ME BY THE NICKNAME nickname.
   
   'Detect user comment.
   NickDetect = InStr(1, TestSentence, " MY NICKNAME IS ", vbTextCompare)
   NickStart = NickDetect + Len(" MY NICKNAME IS ")
   If NickDetect = 0 Then
      NickDetect = InStr(1, TestSentence, " MY NICK NAME IS ", vbTextCompare)
      NickStart = NickDetect + Len(" MY NICK NAME IS ")
   End If
   If NickDetect = 0 Then
      NickDetect = InStr(1, TestSentence, " MY NICKNAMES IS ", vbTextCompare)
      NickStart = NickDetect + Len(" MY NICKNAMES IS ")
   End If
   If NickDetect = 0 Then
      NickDetect = InStr(1, TestSentence, " MY NICK NAMES IS ", vbTextCompare)
      NickStart = NickDetect + Len(" MY NICK NAMES IS ")
   End If
   If NickDetect = 0 Then
      NickDetect = InStr(1, TestSentence, " MY NICKNAME ", vbTextCompare)
      NickStart = NickDetect + Len(" MY NICKNAME ")
   End If
   If NickDetect = 0 Then
      NickDetect = InStr(1, TestSentence, " MY NICK NAME ", vbTextCompare)
      NickStart = NickDetect + Len(" MY NICK NAME ")
   End If
   If NickDetect = 0 Then
      NickDetect = InStr(1, TestSentence, " THE NICKNAME ", vbTextCompare)
      NickStart = NickDetect + Len(" THE NICKNAME ")
   End If
   If NickDetect = 0 Then
      NickDetect = InStr(1, TestSentence, " THE NICK NAME ", vbTextCompare)
      NickStart = NickDetect + Len(" THE NICK NAME ")
   End If
   
   If NickStart > 0 And NickStart < Len(TestSentence) Then  'If Nickname exists then extract it from the sentence.
      Nickname = Mid(TestSentence, NickStart, (Len(TestSentence) - NickStart))
      Nickname = Trim(Nickname)
   
   'Process the user's requested nickname for proper capitalization.
   If HalBrain.CountInstances(" ", Nickname) > 0 Then  'Is a multiple word nickname.
      NickArray = Split(Nickname, " ", -1, vbTextCompare)
      If (IsArray(NickArray) = True And UBound(NickArray) > -1) Then
         Nickname = ""
         For X = 0 To UBound(NickArray) 
            LeftChar = Left(NickArray(X), 1)  
            If (Asc(LeftChar) > 64 And Asc(LeftChar) < 91) Then  'Check if first letter is capitalized.
               'Make sure only the first letter is capitalized.
               'If Nickname is all caps then Hal will make it all lowercase by default.
               'If Nickname is already all lowercase then leave it alone.
               Nickname = Nickname & " " & LeftChar & LCase(Mid(NickArray(X), 2, Len(NickArray(X))))  
            Else
               Nickname = Nickname & " " & LCase(NickArray(X))
            End If
         Next
      End If
   Else  'Is a single word nickname.
      LeftChar = Left(Nickname, 1)  
      If (Asc(LeftChar) > 64 And Asc(LeftChar) < 91) Then  'Check if first letter is capitalized.
         'Make sure only the first letter is capitalized.
         'If Nickname is all caps then Hal will make it all lowercase by default.
         'If Nickname is already all lowercase then leave it alone.
         Nickname = LeftChar & LCase(Mid(Nickname, 2, Len(Nickname)))  
      End If
   End If
   Nickname = Trim(Nickname)

      Select Case Int(Rnd * 4) + 1
         Case 1 
            GetResponse = "Is it alright if I call you <quote>" & Nickname & "<quote>? "
         Case 2
            GetResponse = "Should I call you <quote>" & Nickname & "<quote> sometimes? "
         Case 3
            GetResponse = "May I call you <quote>" & Nickname & "<quote> sometimes? "
         Case 4
            GetResponse = "Is it okay to call you <quote>" & Nickname & "<quote>? "
      End Select

      QuestionPending = "HAL CALLS USER BY NICKNAME" 'Triggers the "HAL CALLS USER BY NICKNAME" function above.
      BlockSave = True
   End If
End If 
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'PROCESS: EPHEMERAL KNOWLEDGE
'Some Hal's learned knowledge should be temporary because it is ephemeral in nature.
'Knowledge about weather, season, temperature, etc. are temporary knowledge
'that shouldn't be stored in Hal's permanent brain files. Currently ephemeral knowledge is
'detected and blocked from being saved.
'
'Future versions will detect and save selected knowledge to temporary memory during the current
'session. This memory would be erased after exiting Hal and perhaps should be reset every few hours even 
'if Hal is left on. Currently this function doesn't have a method of temporary storage. Temporary 
'memory will be implemented later.
'
'XTF_SYS_EphemeralDetect.brn
'File contains detection words and/or phrases like:
'weather, rain, sun, temperature, "just finished", breakfast, dinner,
'today, yesterday, minute, seconds, hours.
'
'Example ephemeral sentences:
'"I'm feeling ill today.", "I went to the museum yesterday.", "I just finished lunch."
'A month from now you wouldn't want Hal repeating back to the user that the user just had lunch.
'
'The side effect of blocking file saving is that some sentences will never be saved to Hal's
'knowledge data base. Examples: "Dinner is my favorite meal." should be saved but is blocked, however,
'"I just had dinner." should be blocked because that is only true currently. Hal can't discern 
'between them and blocks both from saving.

EphemeralDetected = False
If HalBrain.TopicSearch(UserSentence, WorkingDir & "XTF_SYS_EphemeralDetect.brn") = "True" Then
   EphemeralDetected = True
   BlockSave = True  'Block file saves when ephemeral knowledge is detected in UserSentence.
End If
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


	'PROCESS: EMOTIONAL REACTIONS
	'We enable Hal's expressions to respond to 
      'common verbal cues. The verbal cues are identified
	'in the editable file emotion.brn
	EmotionalReaction = HalBrain.TopicSearch(UserSentence, WorkingDir & "Emotion.brn")
	Select Case EmotionalReaction
		Case "SURPRISED"
			If Compliment > 0 Then Compliment = 4
			If Compliment = 0 Then Compliment = 2
			If Compliment < 0 Then Compliment = 0
		Case "HAPPY"
			If Compliment = 0 Then Compliment = 2
			If Compliment < 0 Then Compliment = 0
		Case "SOBER"
		    If Compliment < 4 Then Compliment = 0
			If Compliment = 4 Then Compliment = 2
		Case "ANGRY"
			If Compliment = 0 Then Compliment = -1
			If Compliment > 0 Then Compliment = 0
		Case "SAD"
			If Compliment = 0 Then Compliment = -2
			If Compliment > 0 Then Compliment = 0
	End Select
	If EmotionalReaction <> "" And DebugMode = True Then
		DebugInfo = DebugInfo & "A word in the user's sentence has triggered the emotion of " & EmotionalReaction & VbCrLf
	End If                            
	

	'PROCESS: SMALLTALK KEYWORDS
 	'Here we check to see if Hal can learn keywords
      ' that might work later on in the "smalltalk" routine
	'which is located later in the script. If we seem to 
      'have usable keywords for smalltalk, we preserve
	'them using CurrentSubject as our storage memory. Note 
      'that this routine must capture a phrase into
	'CurrentSubject early enough in the script so that 
      'Hal can use the information immediately (on the
	'current conversational exchange) rather than the next one.
	If HalBrain.CheckLinkingVerb(UserSentence) = True Then
		LearnInfo = HalBrain.Learn(UserSentence)
		LearnKeyword = HalBrain.DecodeVar(LearnInfo, "LearnKeyword")
		LearnKeyword2 = HalBrain.DecodeVar(LearnInfo, "LearnKeyword2")
		If Len(Learnkeyword2) > 3 And Len(LearnKeyword2) < 9 Then CurrentSubject = LearnKeyword2
		If Len(Learnkeyword) > 3 And Len(LearnKeyword) < 17 Then CurrentSubject = LearnKeyword
		CurrentSubject = Replace(" " & CurrentSubject & " ", " SOME ", " ", 1, -1, vbTextCompare)
		CurrentSubject = Replace(" " & CurrentSubject & " ", " SOMETIMES ", " ", 1, -1, vbTextCompare)
		CurrentSubject = Replace(" " & CurrentSubject & " ", " OFTEN ", " ", 1, -1, vbTextCompare)
		CurrentSubject = Replace(" " & CurrentSubject & " ", " OCCASIONALLY ", " ", 1, -1, vbTextCompare)
		CurrentSubject = Trim(CurrentSubject)
		If DebugMode = True And Len(CurrentSubject) > 3 Then
			DebugInfo = DebugInfo & "A new smalltalk keyword has been found and has been made the current subject: " & CurrentSubject & VbCrLf
		End If
	End If
                   
	'PROCESS: BLOCK LEARNING IF HAL'S NAME IS DETECTED
	'Here we check to see if the user is calling Hal by name; if the user is doing so,
	'it's better not to save the sentence for re-use, since it usually makes the 
	'pronoun-reversed sentence sound clumsy or incorrect:
	If InStr(1, UserSentence, ComputerName, vbTextCompare) > 0 Then BlockSave = True
	If InStr(1, OriginalSentence, ComputerName, vbTextCompare) > 0 Then BlockSave = True

	'RESPOND: USER REPEATING
	'If the user says the same thing more than once in a row, Hal will point this out.
'=vonsmith= Added GetResponseBlock
	If Trim(UCase(UserSentence)) = Trim(UCase(PrevUserSent)) And GetResponseBlock <> True Then
		GetResponse = GetResponse & HalBrain.ChooseSentenceFromFile(WorkingDir & "userrepeat.brn") & VbCrLf
		DebugInfo = DebugInfo & "The user has said the same thing twice in a row and a comment has been made about it: " & GetResponse & VbCrLf
	End If

	'RESPOND: CALL GREETING FUNCTION
	'This function takes care of greetings and good-byes, to make a good first and last impression.
	'This function is located in this script and is editable.
	HalGreeting = Trim(Greetings(" " & HalBrain.AlphaNumericalOnly(UserSentence) & " ", PrevSent, PrevUserSent, WorkingDir))
'=vonsmith= Added GetResponseBlock
	If HalGreeting <> "" And GetResponseBlock <> True Then
		GetResponse = GetResponse & HalGreeting & VbCrLf
		DebugInfo = DebugInfo & "The user has either given Hal a greeting or farewell, and Hal has responded to it: " & HalGreeting & VbCrLf
'=vonsmith= Added ShortPhrase reset.
        ShortPhrase = ""
        BlockSave = True  'When the user is saying hello or good bye don't save the user response.
	End If


	'RESPOND: USER SHORT PHRASES
	'=vonsmith= This function has been toward the top.


	'RESPOND: CHANGE SUBJECT
	'If the user asks Hal to change the subject, Hal will do so on request.
'=vonsmith= Added GetResponseBlock
	If HalBrain.TopicSearch(UserSentence, WorkingDir & "ChangeTopic.brn") = "True" And GetResponseBlock <> True Then
		GetResponse = GetResponse & HalBrain.ChooseSentenceFromFile(WorkingDir & "topic.brn")
		DebugInfo = DebugInfo & "The user has requested to change the topic and Hal has done so: " & GetResponse & VbCrLf
	End If


'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'RESPOND: TELL JOKE AT USER'S REQUEST
'==vonsmith== 01-25-04
'If the user asks Hal to tell a joke, Hal will do so on request.
If HalBrain.TopicSearch(UserSentence, WorkingDir & "XTF_SYS_JokeDetect.brn") = "True" And GetResponseBlock <> True Then
   GetResponse = GetResponse & HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_Joke.brn")
   BlockSave = True  'Don't save User input when requesting a joke.
   DebugInfo = DebugInfo & "The user has requested Hal to tell a joke and Hal has done so: " & GetResponse & VbCrLf
End If
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'RESPOND: HAL "MAKES A FACE" AT USER'S REQUEST
'(c) 2004 Scott Higgins. Portions of this script are copyright by Scott Higgins, aka: =vonsmith=
'This script shall not be sold or used for any purpose unless specifically authorized by the author
'in writing. Personal (non-business) use of this script is free for users of Ultra Hal Assistant.
'This is an new function written by =vonsmith= , version 02/04/04.

'This function only works with Haptek characters.
'If the user asks Hal to "make a face", Hal will do so on request.
'If the user asks repeatedly then Hal will get irritated and refuse.

'CHECK USERSENTENCE FOR USER REQUEST:
XTF_FaceDetect = ""

'Preprocess TestSentence.
TestSentence = UserSentence
While InStr(1, TestSentence, "  ", vbTextCompare) > 0
   TestSentence = Replace(TestSentence, "  ", " ", 1, -1, vbTextCompare) 'Replace multiple spaces with single spaces.
Wend

'Detect User Request.     
If InStr(1, TestSentence, " FACE ", 1) > 0 Or InStr(1, TestSentence, " LOOK ", 1) > 0 Then
   XTF_PhraseStart = InStr(1, TestSentence, " MAKE A ", 1)
   If XTF_PhraseStart = 0 Then XTF_PhraseStart = InStr(1, TestSentence, " MAKE AN ", 1)
   If XTF_PhraseStart = 0 Then XTF_PhraseStart = InStr(1, TestSentence, " MAKE ANY ", 1)
   If XTF_PhraseStart = 0 Then XTF_PhraseStart = InStr(1, TestSentence, " MAKE ANOTHER ", 1)
   If XTF_PhraseStart = 0 Then XTF_PhraseStart = InStr(1, TestSentence, " MAKE MY ", 1)
   If XTF_PhraseStart = 0 Then XTF_PhraseStart = InStr(1, TestSentence, " MAKE JUST ", 1)
   If XTF_PhraseStart = 0 Then XTF_PhraseStart = InStr(1, TestSentence, " MAKE ONE ", 1)
   If XTF_PhraseStart = 0 Then XTF_PhraseStart = InStr(1, TestSentence, " SHOW YOU MY ", 1)
   If XTF_PhraseStart = 0 Then XTF_PhraseStart = InStr(1, TestSentence, " SHOW YOU A ", 1)
   If XTF_PhraseStart = 0 Then XTF_PhraseStart = InStr(1, TestSentence, " SHOW YOU AN ", 1)
   If XTF_PhraseStart = 0 Then XTF_PhraseStart = InStr(1, TestSentence, " SHOW YOU ANOTHER ", 1)
   If XTF_PhraseStart = 0 Then XTF_PhraseStart = InStr(1, TestSentence, " SHOW YOU ANY ", 1)
   If XTF_PhraseStart = 0 Then XTF_PhraseStart = InStr(1, TestSentence, " DO A ", 1)
   If XTF_PhraseStart = 0 Then XTF_PhraseStart = InStr(1, TestSentence, " DO AN ", 1)
   If XTF_PhraseStart = 0 Then XTF_PhraseStart = InStr(1, TestSentence, " DO ANOTHER ", 1)
   If XTF_PhraseStart = 0 Then XTF_PhraseStart = InStr(1, TestSentence, " DO MY ", 1)
                                                             
   If XTF_PhraseStart > 0 Then
      If InStr(XTF_PhraseStart, TestSentence, " A FACE ", 1) > 0 Or InStr(XTF_PhraseStart, TestSentence, " ANOTHER FACE ", 1) > 0 Or InStr(XTF_PhraseStart, TestSentence, " ANY FACE ", 1) > 0 Or InStr(XTF_PhraseStart, TestSentence, " MORE FACE ", 1) > 0 Then
         XTF_FaceDetect = " SILLY "
      Else   
         XTF_FaceStart = InStr(XTF_PhraseStart, TestSentence, " FACE ", 1) + 1
         If XTF_FaceStart = 1 Then XTF_FaceStart = InStr(XTF_PhraseStart, TestSentence, " LOOK ", 1) + 1
         If XTF_FaceStart > 1 Then
            XTF_FaceDetect = Mid(TestSentence, XTF_PhraseStart, (XTF_FaceStart - XTF_PhraseStart))
         End If
      End If
   End If                                  
End If
                          
'Prevent erroneous file saves from user not making the request properly.
If (XTF_FaceDetect = "" And InStr(1, TestSentence, " FACE ", 1) > 0 And (InStr(1, TestSentence, " MAKE A", 1) > 0 Or InStr(1, TestSentence, " SHOW YOU ", 1) > 0)) Then BlockSave = True
'Randomly reset MakeFaceCount on a low probability.
If Int(Rnd * 100) < 5 And MakeFaceCount > 4 Then
   MakeFaceCount = 2  
   MakeFaceException = True
End If   
'Randomly make a face on exception, even if Hal is tired of it.
If (Int(Rnd * 100) < 10 And MakeFaceCount < 4) Then MakeFaceException = True  
'Allow special case reset by the user for testing.
If InStr(1, TestSentence, ComputerName & " RESET MAKE A FACE ", 1) Then MakeFaceCount = 0

'MAKE A FACE OR NOT:
If (XTF_FaceDetect <> "" And GetResponseBlock <> True) Then 
   If (((MakeFaceCount > 3) Or (MakeFaceCount > 0 And Int(Rnd * 10) < 2)) And MakeFaceException <> True) Then  'Hal's tired of making faces.
      Select Case MakeFaceCount
         Case 1
            GetResponse = "<UserName>, not again. Maybe later."
            XTF_Emotion = "SURPRISED1"
         Case 2
            GetResponse = "I really don't feel like it now."
            XTF_Emotion = "SURPRISED1"
         Case 3
            GetResponse = "no. I've done this several times already."
            XTF_Emotion = "SURPRISED2"
         Case 4
            GetResponse = "really <UserName>, no more for today."
            XTF_Emotion = "ANGRY1"
         Case 5
            GetResponse = "you make a face! I'm happy with mine just like it is."
            XTF_Emotion = "ANGRY2"
         Case 6
            GetResponse = "knock it off " & UserName & "!"
            XTF_Emotion = "ANGRY2"
         Case 7
            GetResponse = "enough already! Do it yourself."
            XTF_Emotion = "ANGRY3"
         Case Else
            GetResponse = "I'm not going to discuss it!"
            If HalBrain.CheckRepetition(GetResponse, PrevSent) = True Then GetResponse = "I told you I'm not going to discuss it!"
            XTF_Emotion = "ANGRY3"
      End Select
      GetResponseBlock = True
      DebugInfo = DebugInfo & "The user has requested Hal to <quote>make a face<quote>, but Hal has refused for now." & VbCrLf
   Else  'Hal will make a face.
      XTF_Face = HalBrain.TopicSearch(" " & XTF_FaceDetect & " ", WorkingDir & "XTF_SYS_FaceDetect.brn")
      If XTF_Face <> "" Then
         If InStr(1, XTF_Face, "SILLYFACE", 1) > 0 Then  'If a silly face is requested then randomly select one.
            Select Case (Int(Rnd * 3) + 1)
               Case 1
                  XTF_Face = "SILLYFACE1"
               Case 2
                  XTF_Face = "SILLYFACE2"
               Case 3
                  XTF_Face = "SILLYFACE3"
            End Select
         End If

         If MakeFaceException = True Then ExceptionResponse = "okay, just this once. "
         Select Case (Int(Rnd * 8) + 1)
            Case 1
               GetResponse = ExceptionResponse & "here it is <UserName>."
            Case 2
               GetResponse = ExceptionResponse & "here you go."
            Case 3
               GetResponse = ExceptionResponse & "here's one."
            Case 4
               GetResponse = ExceptionResponse & "probably not what you expected <UserName>."
            Case 5
               GetResponse = ExceptionResponse & "you asked for it. You got it."
            Case 6
               GetResponse = ExceptionResponse & "this is the best I can do."
            Case 7
               GetResponse = ExceptionResponse & "<UserName>, this is just for you."
            Case 8
               GetResponse = ExceptionResponse & "I hope this was what you expected."
         End Select

         XTF_Emotion = XTF_Face
         DebugInfo = DebugInfo & "The user has requested Hal to <quote>make a face<quote> and Hal has done so." & VbCrLf
      Else
         GetResponse = "I don't know how to do that one."
         DebugInfo = DebugInfo & "The user has requested Hal to <quote>make a face<quote>, but Hal doesn't know how to do the one requested." & VbCrLf
      End If
   End If
   CurrTopic = "FACE"
   MakeFaceCount = MakeFaceCount + 1
   GetResponseBlock = True
   BlockSave = True
End If
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'RESPOND: LOAD USER RELATED TOPICS FILE [THIS SPACE RESERVED, FUNCTION TO ADDED LATER]
'(c) 2004 Scott Higgins. Portions of this script are copyright by Scott Higgins, aka: =vonsmith=
'This script shall not be sold or used for any purpose unless specifically authorized by the author
'in writing. Personal (non-business) use of this script is free for users of Ultra Hal Assistant.
'This is an new function written by =vonsmith=, version XX/XX/XX.

'Function to be added later.
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


	'PROCESS: FOCUS ON TOPIC
    'Entirely replaced by new XTF function by =vonsmith=.
 

	'RESPOND: CHECK FOR AND RESPOND TO COMPLIMENTS
	'First we check to see if the user is talking about Hal:
	If InStr(1, UserSentence, "I'M", 1) Then Aboutme = True
	If InStr(1, UserSentence, "I AM", 1) Then Aboutme = True
	If InStr(1, UserSentence, "I LOOK", 1) Then Aboutme = True
	'If InStr(1, UserSentence, "MY", 1) And InStr(1, UserSentence, " IS ", 1) Then Aboutme = True
	If InStr(1, UserSentence, "MY", 1) And InStr(1, UserSentence, " ARE ", 1) Then Aboutme = True
	'If the user is talking about Hal, we see if a compliment was given
	If Aboutme = True Then Kudo = HalBrain.TopicSearch(UserSentence, WorkingDir & "ComplimentDetect.brn")
	If Len(Kudo) > 0 Then
		If InStr(UserSentence, " NOT ") = 0 Then
  		  	Compliment = Compliment + 1
  		  	CreateCompliment = HalBrain.SentenceGenerator(WorkingDir & "MakeCompliment.brn") 		  
	   		GiveCompliment = HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_ComplimentIntro.brn")
			GiveCompliment = Replace(GiveCompliment, "<Kudo>", Kudo, 1, -1, vbTextCompare)
			GiveCompliment = Replace(GiveCompliment, "<MakeCompliment>", CreateCompliment, 1, -1, vbTextCompare)	    
		End If
		If Compliment > 14 Then GiveCompliment = GiveCompliment + "Compliments are really nice, but I'm kind of getting tired of them." & VbCrLf
		If Compliment > 15 Then
		For I = 1 To (Compliment - 15)
			GiveCompliment = GiveCompliment + " ENOUGH COMPLIMENTS ALREADY. "
		Next
		GiveCompliment = GiveCompliment & VbCrLf
		End If
		If Compliment > 25 Then
		For I = 1 To (Compliment - 25)
			GiveCompliment = GiveCompliment + " YOUR COMPLIMENTS ARE STARTING TO SOUND SO PHONEY "
		Next
		GiveCompliment = GiveCompliment & VbCrLf
		End If
		If Len(Kudo) > 0 And InStr(UserSentence, " NOT ") > 0 Then
			Weird = Int(Rnd * 4)
			Insults = Insults + 1
			If Weird = 0 Then GiveCompliment = GiveCompliment + "I am very " & Kudo & "!" & VbCrLf
			If Weird = 1 Then GiveCompliment = GiveCompliment + "You may think I am not " & Kudo & ", but I am!" & VbCrLf
			If Weird = 2 Then GiveCompliment = GiveCompliment + "You are not " & Kudo & " either!" & VbCrLf
			If Weird >= 3 Then GiveCompliment = GiveCompliment + "Yes I am!" & VbCrLf
		End If
'=vonsmith= Added GetResponseBlock
If GetResponseBlock <> True Then
		GetResponse = GetResponse & GiveCompliment
		DebugInfo = DebugInfo & "Hal has detected a compliment directed at him and is responding to it: " & GiveCompliment & VbCrLf
End If
		AvoidBeingFlag = True
	End If     

	'RESPOND: CALL CAPITALS FUNCTIONS
	'These 2 functions answer questions about US and World Capitals. The functions are built in to the DLL.
	'We add a qualifying word to reduce false triggering of these two functions.
	If InStr(UserSentence, "WHAT") > 0 Or InStr(UserSentence, "WHERE") > 0 Then
		If Len(HalBrain.USCaps(UserSentence)) > 4 Then
			Capitals = Trim(HalBrain.USCaps(UserSentence))
		End If
		If Len(HalBrain.WorldCaps(UserSentence)) > 4 Then
			Capitals = Trim(HalBrain.WorldCaps(UserSentence))
		End If
'=vonsmith= Added GetResponseBlock
		If Capitals <> "" And GetResponseBlock <> True Then
			GetResponse = GetResponse & Capitals & " . " & VbCrLf
			DebugInfo = DebugInfo & "The user was asking about a capital and Hal has given him the answer: " & Capitals & VbCrLf
		End If
	End If


	'RESPOND: DICTIONARY FUNCTION
	'If the user asks Hal to define a word, then access wordnet and define it
    	If WordToLookup = "" Then WordToLookup = HalBrain.SearchPattern(UserSentence, "WHAT DOES THE WORD * MEAN", 1)
    	If WordToLookup = "" Then WordToLookup = HalBrain.SearchPattern(UserSentence, "WHAT DOES * MEAN", 1)
    	If WordToLookup = "" Then WordToLookup = HalBrain.SearchPattern(UserSentence, "* DEFINE THE WORD *", 2)
    	If WordToLookup = "" Then WordToLookup = HalBrain.SearchPattern(UserSentence, "PLEASE DEFINE *", 1)
    	If WordToLookup = "" Then WordToLookup = HalBrain.SearchPattern(UserSentence, "DEFINE *", 1)
    	If WordToLookup = "" Then WordToLookup = HalBrain.SearchPattern(UserSentence, "* DEFINITION OF *", 2)
    	If WordToLookup = "" Then WordToLookup = HalBrain.SearchPattern(UserSentence, "WHAT'S A *", 1)
    	If WordToLookup = "" Then WordToLookup = HalBrain.SearchPattern(UserSentence, "WHAT IS A *", 1)
    	If WordToLookup = "" Then WordToLookup = HalBrain.SearchPattern(UserSentence, "WHATS A *", 1)
    	If WordToLookup = "" Then WordToLookup = HalBrain.SearchPattern(UserSentence, "WHATS AN *", 1)
    	If WordToLookup = "" Then WordToLookup = HalBrain.SearchPattern(UserSentence, "WHAT'S AN *", 1)
    	If WordToLookup = "" Then WordToLookup = HalBrain.SearchPattern(UserSentence, "WHAT IS AN *", 1)
    	If WordToLookup = "" Then WordToLookup = HalBrain.SearchPattern(UserSentence, "WHATS *", 1)
    	If WordToLookup = "" Then WordToLookup = HalBrain.SearchPattern(UserSentence, "WHAT'S *", 1)
    	If WordToLookup = "" Then WordToLookup = HalBrain.SearchPattern(UserSentence, "WHAT IS *", 1)
    	WordToLookup = Trim(WordToLookup)
    	If WordToLookup <> "" And InStr(WordToLookup, " ") = 0 Then
'=vonsmith= Added GetResponseBlock
        	If WN.LookUpWord(WordToLookup) = True And GetResponseBlock <> True Then
               GetResponse = WordToLookup & ": " & WN.GetDefinition(WN.GuessPartOfSpeech, 1, "D") & ". " & WN.GetDefinition(WN.GuessPartOfSpeech, 1, "S") & ". " & WN.GetDefinition(WN.GuessPartOfSpeech, 1, "E") & "." & VbCrLf
               GetReponseBlock = True    
'=vonsmith= Added BlockSave here. 
               BlockSave = True
        	End If
    	End If

	'RESPOND: DEDUCTIVE REASONING
	'This routine learns deductive reasoning in the form:  A = B ; B = C; therefore A = C  
	'It detects sentences in the form If-Then to accommplish this. For example:
	'	User:  If Molly weighs 400 pounds, then Molly is overweight.
	'	Ultra Hal: I understand the implication.
	'	User:  If Molly is overweight, then Molly's health is in danger.
	'	Ultra Hal:  I see the relationship.
	'	User:  Molly weighs 400 pounds.
	'	Ultra Hal:  Molly's health is in danger.
	IfPart = Trim(HalBrain.SearchPattern(UserSentence, "IF * THEN *", 1))
	ThenPart = Trim(HalBrain.SearchPattern(UserSentence, "IF * THEN *", 2))

	'If the sentence is an If-Then statement then record it.
	If Len(IfPart) > 10 And Len(ThenPart) > 10 And BlockSave = False Then
       BlockSave = True  'Block saving input elsewhere since the user input will saved here.
       IfPart = HalBrain.AlphaNumericalOnly(IfPart)
       ThenPart = HalBrain.AlphaNumericalOnly(ThenPart)
       HalBrain.AppendFile WorkingDir & "deductive.brn", """" & IfPart & """,""" & ThenPart & """"
       '=vonsmith= Added GetResponseBlock
       If GetResponseBlock <> True Then
          Select Case (Int(Rnd * 5) + 1)
             Case 1
                GetResponse = GetResponse & " I see the relationship. " & VbCrLf
             Case 2
                GetResponse = GetResponse & " I understand the connection. " & VbCrLf
             Case 3
                GetResponse = GetResponse & " Yes, I see what you mean. " & VbCrLf
             Case 4
                GetResponse = GetResponse & " Oh, I see the cause and effect. " & VbCrLf
             Case 5
                GetResponse = GetResponse & " Yes, I get that clearly. " & VbCrLf
          End Select
		  DebugInfo = DebugInfo & "Hal has found an If-Then statement from the user and has recorded it in Hal's deductive reasoning brain. " & VbCrLf
       End If
	'Else if the sentence is not an If-Then statement see if it uses an assertion previously recorded
	'and respond accordinly
	Else
		Assertion = UserSentence
		'Modified by =vonsmith= to use random number of connections for more variety.
		For I = 1 To (Int(Rnd * 3) + 2)
		'Go through a maximum of 5 connections (prevents circular reasoning deductions)
'ORIG: For I = 1 To 5
			Deduction = HalBrain.TopicSearch(Assertion, WorkingDir & "deductive.brn")
			If Deduction <> "" Then
				LastGoodDeduction = Deduction
				Assertion = Deduction
			Else
				Exit For 'No more connections, so no need to continue loop
			End If
		Next
		If LastGoodDeduction <> "" Then
			'Make sure the deduction hasn't just been stated by the User or Hal
            '=vonsmith= Added GetResponseBlock
			If HalBrain.CheckRepetition(LastGoodDeduction, UserSentence) = False And HalBrain.CheckRepetition(LastGoodDeduction, PrevSent) = False And HalBrain.CheckRepetition(LastGoodDeduction, PrevUserSent) = False And GetResponseBlock <> True Then 
				GetResponse = " " & GetResponse & "." & VbCrLf & " " & LastGoodDeduction & " . " & VbCrLf
				DebugInfo = DebugInfo & "Hal has responded using deductive reasoning." & VbCrLf
                GetResponseBlock = True
			End If
		End If
	End If

'RESPOND: CHECK FOR APOLOGIES
'=vonsmith= Improved the apology function.
'	If InStr(1, UserSentence, "not", vbTextCompare) = 0 And (InStr(1, UserSentence, "sorry", vbTextCompare) > 0 And (InStr(1, UserSentence, "you're", vbTextCompare) > 0 Or InStr(1, UserSentence, "you are", vbTextCompare) > 0)) Or (InStr(1, UserSentence, "logize", vbTextCompare) > 0 And InStr(1, UserSentence, "you", vbTextCompare) > 0) Then
If HalBrain.TopicSearch(UserSentence, WorkingDir & "XTF_SYS_apologydetect.brn") = "True" Then
   GetResponse = HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_apology.brn")
   GetResponseBlock = True
   If Insults > 1 Then Insults = Insults - 1
   If Hate > 1 Then Hate = Hate - 1
   If Swear > 1 Then Swear = Swear - 1
   If Insults < 3 Then Insults = 0
   If Hate < 3 Then Hate = 0
   If Swear < 3 Then Swear = 0
   DebugInfo = DebugInfo & "The user has appologized to Hal and Hal has responded to the apology and changed his emotions: " & GetResponse & VbCrLf
End If

	'RESPOND: CALL INSULT HATE SWEAR FUNCTION
	'This function will check for insults and swearing and respond to them. It is built into this script,
	'so you can edit it.
	CheckInsult = Trim(Insult(UserSentence, Insults, Hate, Swear, WorkingDir))
'=vonsmith= Added GetResponseBlock
	If Len(CheckInsult) > 4 And GetResponseBlock <> True Then
		GetResponse = GetResponse & CheckInsult & VbCrLf
		AvoidBeingFlag = True
		DebugInfo = DebugInfo & "The user has insulted Hal and Hal has responded to it: " & CheckInsult & VbCrLf
	End If

	'RESPOND: ZABAWARE KEYWORD MAIN BRAIN PRIORITY 1
	'This function tries getting a response from the Enhanced_Main.brn keyword file. If a keyword or
	'keyphrase is found in top priority, it overrides everything before this function.
	KeyBrain = HalBrain.KeywordBrain(UserSentence, WorkingDir & "Enhanced_Main.brn", False)
'=vonsmith= Added GetResponseBlock	
	If Len(KeyBrain) > 3 And GetResponseBlock <> True Then
		DebugInfo = DebugInfo & "A response has been found in the Enhanced_Main.brn Keyword brain and this response has overwritten any response Hal had already come up with, which was:" & GetResponse & VbCrLf
		GetResponse = KeyBrain & VbCrLf
		DebugInfo = DebugInfo & "The new response is: " & KeyBrain & VbCrLf
	End If

	'RESPOND: CALL MATH FUNCTION
	'This function from the DLL answers simple math questions, whether written out in words or with numerals.
	'If an answer is found, it overrides everything before this function.
	HalMath = HalBrain.HalMath(OriginalSentence) & VbCrLf
'=vonsmith= Added GetResponseBlock
	If Len(HalMath) > 3 And GetResponseBlock <> True Then
		DebugInfo = DebugInfo & "Hal has determined the user's sentence was a math inquiry and Hal has solved it. This response has overwritten any response Hal had already come up with, which was:" & GetResponse & VbCrLf
		GetResponse = HalMath & VbCrLf
		NoChoosing = True
		DebugInfo = DebugInfo & "The new response is: " & HalMath & VbCrLf		
	End If

	'RESPOND NUMBER ADDRESS BACKUP USER KEYWORD BRAIN
	'If the user seems to be asking for specific recall of facts or figures or about numbers
	'and addresses the user's sentence may also be searched in a supplementary user sentence
	'file. This is a redundant method for recalling facts.
	If InStr(UserSentence, "WHAT IS") > 0 And InStr(UserSentence, "WHAT IS NEW ") = 0 And InStr(UserSentence, "CAPITAL") = 0 And InStr(UserSentence, "ADDRESS") > 0 Or InStr(UserSentence, "NUMBER") > 0 Then
		GetResponse = HalBrain.HalFormat(GetResponse)
		HalUserBrain = HalBrain.QABrain(UserSentence, WorkingDir & Trim(UserName) & "user_recall.brn", UserBrainRel)
'=vonsmith= Added GetResponseBlock
		If UserBrainRel > 0 And GetResponseBlock <> True Then
			GetResponse = GetResponse & HalUserBrain & VbCrLf
			DebugInfo = DebugInfo & "The user was requesting to Hal to recall a previously recorded address and Hal has done so: " & HalUserBrain & VbCrLf
		End If
	End If

	'PROCESS: FIGURE OUT CONTEXT
	'If the user's latest sentence is extremely short, such as "Yeah," or if 
	'the user is using pronouns instead of nouns, we add in the previous user's 
	'sentence to help Hal figure out the context of what the user is saying.
	'This is sentence is used in many of the QABrain Database routines
    LongUserSent = UserSentence
    If Len(LongUserSent) < 14 Then AddPrev = True
    If InStr(1, UserSentence, " it ", vbTextCompare) > 0 Then AddPrev = True 
    If InStr(1, UserSentence, " he ", vbTextCompare) > 0 Then AddPrev = True 
    If InStr(1, UserSentence, " she ", vbTextCompare) > 0 Then AddPrev = True 
    If InStr(1, UserSentence, " they ", vbTextCompare) > 0 Then AddPrev = True 
    If InStr(1, UserSentence, " its ", vbTextCompare) > 0 Then AddPrev = True 
    If InStr(1, UserSentence, " his ", vbTextCompare) > 0 Then AddPrev = True 
    If InStr(1, UserSentence, " her ", vbTextCompare) > 0 Then AddPrev = True 
    If InStr(1, UserSentence, " their ", vbTextCompare) > 0 Then AddPrev = True 
    If InStr(1, UserSentence, " him ", vbTextCompare) > 0 Then AddPrev = True 
    If InStr(1, UserSentence, " them ", vbTextCompare) > 0 Then AddPrev = True 
    If InStr(1, UserSentence, " we ", vbTextCompare) > 0 Then AddPrev = True 
    If InStr(1, UserSentence, " us ", vbTextCompare) > 0 Then AddPrev = True 
    If InStr(1, UserSentence, " our ", vbTextCompare) > 0 Then AddPrev = True 
    If AddPrev = True Then 
    	LongUserSent = LongUserSent & " " & PrevUserSent
    	DebugInfo = DebugInfo & "Hal has decided to add the user's previous sentence to this one to figure out the context: " & LongUserSent & VbCrLf
    End If


'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'PROCESS: XTF TOPIC FOCUS FUNCTION
'(c) 2004 Scott Higgins. Portions of this script are copyright by Scott Higgins, aka: =vonsmith=
'This script shall not be sold or used for any purpose unless specifically authorized by the author
'in writing. Personal (non-business) use of this script is free for users of Ultra Hal Assistant.
'This is an entirely new function written by =vonsmith= , version 02-02-04a.
'
'Because of the complexity of this script the author doesn't not recommend that the end user make any
'changes. Many of the XTF subfunctions are highly interrelated and even minor changes may cause unintended
'and difficult to trace side effects. If you do intend to experiment with this script then make certain
'you have a backup of the original XTF script before proceeding.
'
'This is the XTF (eXtended Topic Focus) function. It replaces the original Topic Focus method entirely.
'It consists of 9 sections:
'  1) SUBJECT FRAGMENT SEARCH         
'        Search for valid sentence fragments or single word that contains a Subject of discussion.
'  2) DERIVE TOPIC FROM SUBJECT       
'        Derive multiple word and single word, both plural and singular, topics from the Subject.
'  3) CREATE RELATED TOPICS RESPONSE  
'        This is the function that responds to the "CREATE RELATED TOPICS INQUIRY" section.                               
'        If Hal believes two topics are related he will ask the user to confirm it.
'  4) SEARCH FOR PREVTOPIC MATCH
'        This function searchs the UserSentence exhaustively looking for a match in the current sentence
'        to the prev sentence topic. Hal makes every possible attempt to stay on the same topic as long
'        as the user wants to.
'  5) QA BRAIN SEARCH
'        By this point Hal has identified a current topic and is getting a GetResponse as a reply to the user.
'  6) WRITE TOPICS FOUND TO FILES
'        Hal discovers new topics from the discussion and save them to various topic files. Hal "learns" to
'        use new topics to help stay focused on a topic in future discussions.
'  7) CREATE RELATED TOPICS INQUIRY
'        When Hal suspects a relationship between two topics he will create an inquiry to ask the user to 
'        confirm or deny that two topics are related. If they are related like "sand" and "beach" might be
'        then Hal will remember that any UserSentence about sand may be related to following UserSentences
'        about beaches; and vice versa.
'  8) WRITE NEW QA DATA TO FILES
'        This function writes the current QA data from the UserSentence to the user specific and general (alluser)
'        QA files. (alluser) data files contain QA data that will be shared among all user discussions.
'  9) PRESERVE VARIABLES
'        Hal preserves some variables to be used in the next cycle of discussion with the user.

'INITIALIZE SOME VARIABLES:
Dim BaseTopicSingular, BaseTopicPlural, DetailTopicSingular, DetailTopicPlural, DebugText
BaseTopicSingular = ""
BaseTopicPlural = ""
DetailTopicSingular = ""
DetailTopicPlural = ""
DebugText = ""

'PREPROCESS SENTENCE:
TestSentence = UserSentence
'The next line takes care of forms like, "AREN'T YOU HAPPY?", by modifying it to "ARE YOU HAPPY?"
If InStr(1, TestSentence, " AREN'T ", vbTextCompare) = 1 Then TestSentence = Replace(TestSentence, " AREN'T ", " ARE ", 1, -1, vbTextCompare)
TestSentence = Replace(TestSentence, "'RE ", " ARE ", 1, -1, vbTextCompare)
TestSentence = Replace(TestSentence, " WON'T ", " WILL NOT ", 1, -1, vbTextCompare)
TestSentence = Replace(TestSentence, " CAN'T ", " CAN NOT ", 1, -1, vbTextCompare)
TestSentence = Replace(TestSentence, "N'T ", " NOT ", 1, -1, vbTextCompare)
TestSentence = Replace(TestSentence, " IT'S ", " IT IS ", 1, -1, vbTextCompare)
TestSentence = Replace(TestSentence, " WHAT'S ", " WHAT IS ", 1, -1, vbTextCompare)
TestSentence = Replace(TestSentence, " THAT'S ", " THAT IS ", 1, -1, vbTextCompare)
TestSentence = Replace(TestSentence, " WHEN'S ", " WHEN IS ", 1, -1, vbTextCompare)
TestSentence = Replace(TestSentence, " WHERE'S ", " WHERE IS ", 1, -1, vbTextCompare)
TestSentence = Replace(TestSentence, " WHO'S ", " WHO IS ", 1, -1, vbTextCompare)
TestSentence = Replace(TestSentence, " HOW'S ", " HOW IS ", 1, -1, vbTextCompare)
TestSentence = Replace(TestSentence, " I'M ", " I AM ", 1, -1, vbTextCompare)

TestSentence = Replace(TestSentence, ",", " ", 1, -1, vbTextCompare)
TestSentence = Replace(TestSentence, "?", " ", 1, -1, vbTextCompare)
TestSentence = Replace(TestSentence, "!", " ", 1, -1, vbTextCompare)
TestSentence = Replace(TestSentence, ".", " ", 1, -1, vbTextCompare)

While InStr(1, TestSentence, "  ", vbTextCompare) > 0 'Replace multiple spaces with single spaces.
   TestSentence = Replace(TestSentence, "  ", " ", 1, -1, vbTextCompare)
Wend


'DEBUG LOG START:
DebugText = DebugText & VbCrLf & "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
DebugText = DebugText & VbCrLf & "START ============== XTF DEBUG LOG ============== START"
DebugText = DebugText & VbCrLf & "Log Time: " & Now & VbCrLf

'Eliminate poor Subject words from the Subject. This helps eliminate creating an invalid Subject due to odd grammar.
'Also remove unwanted words, primarily adverbs, ending in "LY " from the Subject.
TestSentence = CleanSentence(TestSentence, WorkingDir) 'Only remove undesireable words ending in "LY ".
PoorSubject = HalBrain.TopicSearch(TestSentence, WorkingDir & "XTF_SYS_FilterSubjectWords.brn")
While PoorSubject <> "" 
   TestSentence = Replace(TestSentence, PoorSubject, " ", 1, -1, vbTextCompare)
   PoorSubject = HalBrain.TopicSearch(TestSentence, WorkingDir & "XTF_SYS_FilterSubjectWords.brn")
Wend

'Add end of sentence marker and make absolutely certain that TestSentence has " " on each end
'before entering the "While" loops.
TestSentence = "  " & Trim(TestSentence) & " " & "<END>" & " " 

DebugText = DebugText & VbCrLf & "PrevSent: (" & PrevSent & ")" & VbCrLf & "OriginalSentence: (" & OriginalSentence & ")" & VbCrLf & "UserSentence:     (" & UserSentence & ")" & VbCrLf & "TestSentence:     (" & TestSentence & ")"& VbCrLf & "PrevTopic:(" & PrevTopic & ")" & VbCrLf & "PrevTopicPlural:(" & PrevTopicPlural & ")" & VbCrLf
    
'SUBJECT FRAGMENT SEARCH:
Dim ForeWord, AftWord, TestSubjectArray, LastWordArray
ForeWordStart = 0
AftWordStart = 0
LastAftWordStart = 0
LastForeWordX = ""
LastAftWordY = ""
Subject = ""
SingleEnded = False
FragmentFound = False
InvalidSubject = False
                                                 
DebugText = DebugText & VbCrLf & "START ========= SUBJECT FRAGMENT SEARCH ========= START" & VbCrLf
DebugText = DebugText & VbCrLf & "0)  Subject:(" & Subject & ")"
DebugText = DebugText & VbCrLf & "    If BaseTopicSingular = """" then run." & VbCrLf 
If BaseTopicSingular = "" Then
   'Initialize Arrays
   ForeWord = Array("I", "YOU", "MY", "YOUR", "OUR", "A", "THE", "THIS", "THAT", "AN", "THEIR", "THEY", "THOSE", "WE", "HER", "HIS", "ITS", "")
   AftWord = Array("IS", "ARE", "DID", "DO", "DOES", "HAS", "HAD", "CAN", "COULD", "MAY", "MIGHT", "MUST", "NEEDS", "WAS", "WENT", "WERE", "WILL", "WOULD", "BECAME", "BECOME", "BECOMES", "APPEAR", "APPEARED", "APPEARS", "FEEL", "FALLS", "FEELS", "FELT", "GET", "GETS", "GOES", "GOT", "GREW", "GROW", "GROWS", "LOOK", "LOOKED", "LOOKS", "OUGHT", "REMAINED", "REMAINS", "RUN", "RUNS", "SEEM", "SEEMED", "SEEMS", "SHALL", "SHOULD", "SMELL", "SMELLED", "SMELLS", "SOUNDED", "SOUNDS", "STAYED", "STAYS", "TASTE", "TASTED", "TASTES", "TOUCHED", "TOUCHES", "TURNED", "TURNS", "NEVER", "HAVE", "MAKE", "MAKES", "SEEMS", "SEEM", "<END>")
   'Search for over 800 types of sentence fragments for a multiple or single word Subjects.
   'Sentence fragments can be in 3 forms: "<ForeWord> * <AftWord>" which is double-ended.
   '             or single-ended such as: "<ForeWord> * " or " * <AftWord>"
   For Y = 0 To UBound(AftWord)
      AftWordStart = InStr(1, TestSentence, " " & AftWord(Y) & " ", vbTextCompare)
      If AftWordStart > 0 Then
         LastForeWordStart = Len(TestSentence)
         For X = 0 To UBound(ForeWord)  'Find the ForeWord furthest from the beginning of the sentence.
            ForeWordStart = InStr(1, TestSentence, " " & ForeWord(X) & " ", vbTextCompare)
            If (ForeWordStart < AftWordStart And ForeWordStart < LastForeWordStart) Then
               For Z = 0 To UBound(ForeWord)
                  ForeWordStart2 = InStr(ForeWordStart + 1, TestSentence, " " & ForeWord(Z) & " ", vbTextCompare)
                  If ForeWordStart2 > ForeWordStart And ForeWordStart2 < AftWordStart Then
                     ForeWordStart = ForeWordStart2
                     X = Z
                     FragmentFound = True
                     Exit For
                  End If 
               Next
               LastAftWordStart = AftWordStart
               LastAftWordY = AftWord(Y)
            End If
            If FragmentFound = True Then Exit For
         Next
         LastForeWordX = ForeWord(X)
         Exit For
      End If
   Next

   If LastForeWordX = "" And LastAftWordY = "<END>" Then InvalidSubject = True
   'Extract Subject.
   If (LastAftWordStart < Len(TestSentence) And LastAftWordStart > ForeWordStart And InvalidSubject <> True) Then
      Subject = ""
      Subject = Mid(TestSentence, ForeWordStart + Len(LastForeWordX) + 1, LastAftWordStart - (ForeWordStart + Len(LastForeWordX)))
      Subject = Trim(Subject)

      'Remove multiple spaces from Subject.
      Subject = Trim(Subject)                                                                                                         
      While InStr(1, Subject, "  ", vbTextCompare) > 0 'Replace multiple spaces with single spaces.
         Subject = Replace(Subject, "  ", " ", 1, -1, vbTextCompare)
      Wend

      If LastForeWordX = "" Then SingleEnded = True  'If true the Subject is "word1 * word2" type fragment, else "* word1" type.
      If LastAftWordY = "<END>" Then SingleEnded = True  'If true the Subject is "word1 * word2" type fragment, else "* word1" type.
   End If

   If Subject <> "" Then
DebugText = DebugText & VbCrLf & "1)  Subject found in UserSentence." & VbCrLf & "    Subject:(" & Subject & ")" & "  SingleEnded:(" & SingleEnded & ")" & VbCrLf & "    LastForeWordX:(" & LastForeWordX & ")  LastAftWordY:(" & LastAftWordY & ")" & VbCrLf & "    Fragment:(" & LastForeWordX & " * " & LastAftWordY & ")" & VbCrLf
      'Process special cases.
      'Test for " AND" and "AND " at the each end of Subject. If either exists, then remove them. An "AND" preceded and followed by a word is a valid Subject.
      If InStr(1, Subject, "AND ", vbTextCompare) = 1 Then Subject = Replace(Subject, "AND ", "", 1, 1, vbTextCompare)
      'If exists, remove the trailing " AND" on Subject.
      If (InStr(1, Subject, " AND", vbTextCompare) > 0 And InStr(1, Subject, " AND", vbTextCompare) = Len(Subject) - 3) Then Subject = Replace(Subject, " AND", "", (Len(Subject) - 3), 1, vbTextCompare)
      'If Subject contains " AND " and is longer than 5 words then Subject = "".
      If (HalBrain.CountInstances(" ", Subject) > 4 And InStr(1, Subject, " AND ", vbTextCompare) > 0) Then Subject = ""
DebugText = DebugText & VbCrLf & "2)  Process ""AND"" type Subjects to block Subjects like:" & VbCrLf & "    ""Dogs and"" or ""and cats""" & VbCrLf & "    Subject:(" & Subject & ")" & "  SingleEnded:(" & SingleEnded & ")" & VbCrLf

      'If the Subject is longer than 4 words or Subject is single-ended, and doesn't contain " AND " then select only the right-most word as Subject.
      'Very long Subjects tend not to be focused on a topic. An exception is made for " AND " compound Subjects.
      If ((HalBrain.CountInstances(" ", Subject) > 3 Or SingleEnded = True) And Not InStr(1, Subject, " AND ", vbTextCompare) > 0) Then
         'Use only the right-most word for the Subject.
         TestSubjectArray = Split(Trim(Subject), " ", -1, vbTextCompare)
         If (IsArray(TestSubjectArray) = True And UBound(TestSubjectArray) > -1) Then
DebugText = DebugText & VbCrLf & "3a) Multi-word, but not "" AND "" compound type Subject." & VbCrLf & "    Subject:(" & Subject & ")" & "  SingleEnded:(" & SingleEnded & ")"
            Subject = Trim(TestSubjectArray(UBound(TestSubjectArray)))
            If Subject <> "" Then
               'Disqualify Subject if the last word is a poor Subject.
               If HalBrain.TopicSearch(" " & Subject & " ", WorkingDir & "XTF_SYS_PoorSubjectWords.brn") <> "" Then Subject = ""
DebugText = DebugText & VbCrLf & "3b) Filter out poor Subjects and for single-ended Subjects just use the last word." & VbCrLf & "    Subject:(" & Subject & ")" & "  SingleEnded:(" & SingleEnded & ")" & VbCrLf
            End If   
         End If
      Else
         'Save complete Subject, either single word or up to 5 words if it is an "AND" compound Subject.
         If Subject <> "" Then
            'If Subject is multiple word then break it into an array to test the last word.
            If HalBrain.CountInstances(" ", Subject) > 0 Then
               TestSubjectArray = Split(Trim(Subject), " ", -1, vbTextCompare)
               If (IsArray(TestSubjectArray) = True And UBound(TestSubjectArray) > -1) Then
                  TestSubject = TestSubjectArray(UBound(TestSubjectArray))
               End If
               'Disqualify Subject if the last word is a poor Subject.
               If HalBrain.TopicSearch(" " & TestSubject & " ", WorkingDir & "XTF_SYS_PoorSubjectWords.brn") <> "" Then Subject = ""
            Else  'Is a single word Subject
               'Disqualify Subject if the last word is a poor Subject.
               If HalBrain.TopicSearch(" " & Subject & " ", WorkingDir & "XTF_SYS_PoorSubjectWords.brn") <> "" Then Subject = ""
            End If
DebugText = DebugText & VbCrLf & "4)  Single word or "" AND "" type Subject." & VbCrLf & "    Subject:(" & Subject & ")" & "  SingleEnded:(" & SingleEnded & ")" & VbCrLf
         End If
      End If
DebugText = DebugText & VbCrLf & "5)  Final Subject:(" & Subject & ")" & "   SingleEnded:(" & SingleEnded & ")" & VbCrLf
   End If

   'Remove multiple spaces from Subject.
   Subject = Trim(Subject)
   While InStr(1, Subject, "  ", vbTextCompare) > 0 'Replace multiple spaces with single spaces.
      Subject = Replace(Subject, "  ", " ", 1, -1, vbTextCompare)
   Wend

End If
DebugText = DebugText & VbCrLf & "END ----------- SUBJECT FRAGMENT SEARCH ----------- END" & VbCrLf & VbCrLf


'DERIVE TOPIC FROM SUBJECT:
'Derive multi-word and single-word forms for both singular and plural topics.
'Derive DetailTopicPlural, DetailTopicSingular, BaseTopicPlural, and BaseTopicSingular.
'Example: If the Subject equals "THE FANCY HORSES ARE FUN TO WATCH" then...
'DetailTopicPlural = "FANCY HORSES"
'DetailTopicSingular = "FANCY HORSE"
'BaseTopicPlural = "HORSES"
'BaseTopicSingular = "HORSE"
Dim SubArray, TempTopicArray
DetailTopic = "" 
CurrTopic = ""
DebugText = DebugText & VbCrLf & "START ======== DERIVE TOPIC FROM SUBJECT ======== START" & VbCrLf
DebugText = DebugText & VbCrLf & "0)  Subject:(" & Subject & ")  BaseTopicSingular:(" & BaseTopicSingular & ")" 
DebugText = DebugText & VbCrLf & "    If (Len(Subject) > 0 And BaseTopicSingular = """") then run." & VbCrLf
If (Len(Subject) > 0 And BaseTopicSingular = "") Then
   If HalBrain.CountInstances(" ", Trim(Subject)) > 0 Then 'Is a multiple word Subject.
      SubArray = Split(Trim(Subject), " ", -1, vbTextCompare)
      If (IsArray(SubArray) = True And UBound(SubArray) > -1) Then
         For X = 0 To (UBound(SubArray) - 1)  'Rebuild multiple word Subject.
            DetailTopic = DetailTopic & " " & SubArray(X)
         Next
         DetailTopicPlural = Subject
         BaseTopicPlural = SubArray(UBound(SubArray))
         BaseTopicSingular = UCase(WN.FindFirstNoun(BaseTopicPlural)) 'Attempt to get singular version if Subject is plural.
         DetailTopicSingular = Trim(DetailTopic & " " & BaseTopicSingular)
         If (BaseTopicSingular = "" Or BaseTopicSingular = BaseTopicPlural) Then  'Search single word topic file for a singular form.
            TempTopic = HalBrain.TopicSearch(" " & BaseTopicPlural & " ", WorkingDir & "XTF_Topics1.brn")
            TempTopicArray = Split(TempTopic, ",", 2, vbTextCompare)
            If (IsArray(TempTopicArray) = True And UBound(TempTopicArray) = 1) Then
               BaseTopicSingular = Trim(TempTopicArray(1))
               DetailTopicSingular = Trim(DetailTopic & " " & BaseTopicSingular)
            Else
               BaseTopicSingular = BaseTopicPlural
               DetailTopicSingular = DetailTopicPlural
            End If
         End If
DebugText = DebugText & VbCrLf & "1)  Multiple word Subject." & VbCrLf & "    DetailTopicPlural:(" & DetailTopicPlural & ")" & "  DetailTopicSingular:(" & DetailTopicSingular & ")" & VbCrLf & "    BaseTopicPlural:(" & BaseTopicPlural & ")" & "  BaseTopicSingular:(" & BaseTopicSingular & ")" & VbCrLf
      End If
   Else 'Is a single word Subject.
      BaseTopicPlural = Subject
      BaseTopicSingular = UCase(WN.FindFirstNoun(BaseTopicPlural)) 'Attempt to get singular version if Subject is plural.
      If (BaseTopicSingular = "" Or BaseTopicSingular = BaseTopicPlural) Then  'Search single word topic file for a singular form.
         TempTopic = HalBrain.TopicSearch(" " & BaseTopicPlural & " ", WorkingDir & "XTF_Topics1.brn")
         TempTopicArray = Split(TempTopic, ",", 2, vbTextCompare)
         If (IsArray(TempTopicArray) = True And UBound(TempTopicArray) = 1) Then
            BaseTopicSingular = Trim(TempTopicArray(1))
         Else
            BaseTopicSingular = BaseTopicPlural
         End If
      End If
DebugText = DebugText & VbCrLf & "2)  Single word Subject." & VbCrLf & "    DetailTopicPlural:(" & DetailTopicPlural & ")" & "  DetailTopicSingular:(" & DetailTopicSingular & ")" & VbCrLf & "    BaseTopicPlural:(" & BaseTopicPlural & ")" & "  BaseTopicSingular:(" & BaseTopicSingular & ")" & VbCrLf
   End If
End If
DebugText = DebugText & VbCrLf & "END ---------- DERIVE TOPIC FROM SUBJECT ---------- END" & VbCrLf & VbCrLf


'CREATE RELATED TOPICS RESPONSE:
'This function is triggered by the flag "QuestionPending" set by
'the "CREATE RELATED TOPICS INQUIRY" Function.
DebugText = DebugText & VbCrLf & "START ====== CREATE RELATED TOPICS RESPONSE ===== START" & VbCrLf
DebugText = DebugText & VbCrLf & "0)  QuestionPending:(" & QuestionPending & ")" & VbCrLf & "    If QuestionPending <> ""CREATE RELATED TOPICS"" then don't run." & VbCrLf 
If QuestionPending = "CREATE RELATED TOPICS" Then
   TFStatus1 = ""
   SkipIt = False
   YesOrNo = ""
   YesOrNo = HalBrain.TopicSearch(UserSentence, WorkingDir & "XTF_SYS_YesNoDetect.brn")
   If YesOrNo = "YES" Then
      RelStatus = "True"
      RelStatusNot = "False"
DebugText = DebugText & VbCrLf & "1a) User response was ""Yes"" to Hal's inquiry about relatedness." & VbCrLf & "    A related topics ""True"" will be written to the proper file." & VbCrLf
   ElseIf YesOrNo = "NO" Then
      RelStatus = "False"
      RelStatusNot = "True"
DebugText = DebugText & VbCrLf & "1b) User response was ""No"" to Hal's inquiry about relatedness." & VbCrLf & "    A related topics ""False"" will be written to the proper file." & VbCrLf
   Else
      SkipIt = True
DebugText = DebugText & VbCrLf & "1c) User response was neither ""Yes"" or ""No"" to Hal's inquiry about relatedness." & VbCrLf & "    No related topics will be written to any file." & VbCrLf
   End If

   If SkipIt <> True Then  'User must have answered "Yes" or "No" to Hal's inquiry about relatedness.
      If RelPrevTopic <> "" Then
         'Write related topic to converse file. Only base topics, either singular and/or plural are available for PrevTopic.
         TFStatus1 = HalBrain.TopicSearch(RelPrevTopic, WorkingDir & "XTF_" & Trim(RelBaseTopicSingular) & "_Related.brn")
         If (TFStatus1 = "" Or TFStatus1 = RelStatusNot) Then
            HalBrain.AppendFile WorkingDir & "XTF_" & Trim(RelBaseTopicSingular) & "_Related.brn", """" & " " & Trim(RelPrevTopic) & " " & """,""" & RelStatus & """"
         End If
DebugText = DebugText & VbCrLf & "2)  RelPrevTopic:(" & RelPrevTopic & ")"
DebugText = DebugText & VbCrLf & "    TFStatus1:(" & TFStatus1 & ")  RelStatusNot:(" & RelStatusNot & ")  If (TFStatus1 = "" Or TFStatus1 = RelStatusNot) then write to the file."
DebugText = DebugText & VbCrLf & "    Write RelPrevTopic to RelBaseTopicSingular related file:(" & "XTF_" & Trim(RelBaseTopicSingular) & "_Related.brn)"
DebugText = DebugText & VbCrLf & "    Data written:(" & """" & " " & Trim(RelPrevTopic) & " " & """,""" & RelStatus & """" & ")" & VbCrLf
      End If

      If RelPrevTopicPlural <> "" Then
         TFStatus1 = HalBrain.TopicSearch(RelPrevTopicPlural, WorkingDir & "XTF_" & Trim(RelBaseTopicSingular) & "_Related.brn")
         If (TFStatus1 = "" Or TFStatus1 = RelStatusNot) Then
            HalBrain.AppendFile WorkingDir & "XTF_" & Trim(RelBaseTopicSingular) & "_Related.brn", """" & " " & Trim(RelPrevTopicPlural) & " " & """,""" & RelStatus & """"
         End If
DebugText = DebugText & VbCrLf & "3)  RelPrevTopicPlural:(" & RelPrevTopicPlural & ")"
DebugText = DebugText & VbCrLf & "    TFStatus1:(" & TFStatus1 & ")  RelStatusNot:(" & RelStatusNot & ")  If (TFStatus1 = "" Or TFStatus1 = RelStatusNot) then write to the file."
DebugText = DebugText & VbCrLf & "    Write RelPrevTopicPlural to RelBaseTopicSingular related file:(" & "XTF_" & Trim(RelBaseTopicSingular) & "_Related.brn)"
DebugText = DebugText & VbCrLf & "    Data written:(" & """" & " " & Trim(RelPrevTopicPlural) & " " & """,""" & RelStatus & """" & ")" & VbCrLf
      End If
   
      If RelBaseTopicSingular <> "" Then
         TFStatus1 = HalBrain.TopicSearch(RelBaseTopicSingular, WorkingDir & "XTF_" & Trim(RelPrevTopic) & "_Related.brn")
         If (TFStatus1 = "" Or TFStatus1 = RelStatusNot) Then
            HalBrain.AppendFile WorkingDir & "XTF_" & Trim(RelPrevTopic) & "_Related.brn", """" & " " & Trim(RelBaseTopicSingular) & " " & """,""" & RelStatus & """"
         End If
DebugText = DebugText & VbCrLf & "4)  RelBaseTopicSingular:(" & RelBaseTopicSingular & ")"
DebugText = DebugText & VbCrLf & "    TFStatus1:(" & TFStatus1 & ")  RelStatusNot:(" & RelStatusNot & ")  If (TFStatus1 = "" Or TFStatus1 = RelStatusNot) then write to the file."
DebugText = DebugText & VbCrLf & "    Write RelBaseTopicSingular to RelPrevTopic related file:(" & "XTF_" & Trim(RelPrevTopic) & "_Related.brn)"
DebugText = DebugText & VbCrLf & "    Data written:(" & """" & " " & Trim(RelBaseTopicSingular) & " " & """,""" & RelStatus & """" & ")" & VbCrLf
      End If
      
      If RelBaseTopicPlural <> "" Then
         TFStatus1 = HalBrain.TopicSearch(RelBaseTopicPlural, WorkingDir & "XTF_" & Trim(RelPrevTopic) & "_Related.brn")
         If (TFStatus1 = "" Or TFStatus1 = RelStatusNot) Then
            HalBrain.AppendFile WorkingDir & "XTF_" & Trim(RelPrevTopic) & "_Related.brn", """" & " " & Trim(RelBaseTopicPlural) & " " & """,""" & RelStatus & """"
         End If
DebugText = DebugText & VbCrLf & "5)  RelBaseTopicPlural:(" & RelBaseTopicPlural & ")"
DebugText = DebugText & VbCrLf & "    TFStatus1:(" & TFStatus1 & ")  RelStatusNot:(" & RelStatusNot & ")  If (TFStatus1 = "" Or TFStatus1 = RelStatusNot) then write to the file."
DebugText = DebugText & VbCrLf & "    Write RelBaseTopicPlural to RelPrevTopic related file:(" & "XTF_" & Trim(RelPrevTopic) & "_Related.brn)"
DebugText = DebugText & VbCrLf & "    Data written:(" & """" & " " & Trim(RelBaseTopicPlural) & " " & """,""" & RelStatus & """" & ")" & VbCrLf
      End If

      If YesOrNo <> "" Then
         Select Case Int(Rnd * 7) + 1
            Case 1 
               GetResponse = "Thanks, I'll keep that in mind."
            Case 2
               GetResponse = "Okay, that's what I thought."
            Case 3
               GetResponse = "Thanks, I'll remember that."
            Case 4
               GetResponse = "Thanks, I wasn't certain."
            Case 5
               GetResponse = "Okay, I got it."
            Case 6
               GetResponse = "Okay, I thought so."
            Case 7
               GetResponse = "Thanks, I just learned something new."
         End Select
      End If

      'The user's "Yes" answer precludes a Subject, so stay on topic by using RelPrevTopic.
      'Set Topic variables to allow a GetResponse in addition to the answer from this 'related' function.
      TempPrevTopic = RelPrevTopic
      CurrTopic = RelPrevTopic
DebugText = DebugText & VbCrLf & "6)  CurrTopic:(" & CurrTopic & ")  RelPrevTopic:(" & RelPrevTopic & ")  TempPrevTopic:(" & TempPrevTopic & ")  BlockSave:(" & BlockSave & ")" & VbCrLf
   
      'Reinitialize related variables.
      QuestionPending = ""
      RelPrevTopic = ""
      RelPrevTopicPlural = ""
      RelDetailTopicPlural = ""
      RelDetailTopicSingular = ""   
      RelBaseTopicPlural = ""
      RelBaseTopicSingular = ""   
   End If
End If
DebugText = DebugText & VbCrLf & "END -------- CREATE RELATED TOPICS RESPONSE ------- END" & VbCrLf & VbCrLf


'SEARCH FOR PREVTOPIC MATCH:
'Search UserSentence for known topics, match to PrevTopic if possible.
Dim WordCount, TempTopic1, TempTopic2, SameTopic, BlockTopicSave, BlockPrevTopicSave
WordCount = 0
TempTopic1 = ""
TempTopic2 = ""
SameTopic = False
BlockTopicSave = False  'For user generated 'related' topics file save.
BlockPrevTopicSave = False  'Blocks the saving of the CurrTopic to PrevTopic.
TestSentence = " " & UserSentence & " "
'Note: If SameTopic is set True then it indicates that the CurrTopic has been set to PrevTopic.
'
'If BaseTopicSingular exists and equals PrevTopic then set CurrTopic to PrevTopic. User hasn't changed topic.
'Else search the UserSentence for a topic match to PrevTopic or a search for a new general topic.
DebugText =  DebugText & VbCrLf & "START ======== SEARCH FOR PREVTOPIC MATCH ======= START" & VbCrLf
DebugText =  DebugText & VbCrLf & "0)  BaseTopicSingular:(" & BaseTopicSingular & ")  PrevTopic:(" & PrevTopic & ")  CurrTopic:(" & CurrTopic & ")"
DebugText =  DebugText & VbCrLf & "    If (BaseTopicSingular <> """" And BaseTopicSingular = PrevTopic And CurrTopic = """") then run." & VbCrLf
If (BaseTopicSingular <> "" And BaseTopicSingular = PrevTopic And CurrTopic = "") Then  
   CurrTopic = PrevTopic
   SameTopic = True
DebugText = DebugText & VbCrLf & VbCrLf & "1)  BaseTopicSingular exists and is equal to PrevTopic. CurrTopic set to PrevTopic:(" & PrevTopic & ")"
DebugText = DebugText & VbCrLf & "    CurrTopic:(" & CurrTopic & ")  If CurrTopic = """" then run." & VbCrLf
ElseIf CurrTopic = "" Then
DebugText =  DebugText & VbCrLf & "2)  Search for multiword phrases that match PrevTopic." & VbCrLf & "    PrevTopic:(" & PrevTopic & ")  CurrTopic:(" & CurrTopic & ")" & VbCrLf
   'Check 5 word topics first, then 4, and then 3, etc. 1 word topics are treated separately afterward.
   'Checking the longest topic phrases first ensures the most detailed (focused) topics are preferentially found first.
   For WordCount = 5 To 2 Step -1  
DebugText = DebugText & VbCrLf & "2a) Search for multiword phrases that match PrevTopic." & VbCrLf & "    PrevTopic:(" & PrevTopic & ")"
DebugText = DebugText & VbCrLf & "    Searching multiword phrases (" & WordCount & ") words long." & VbCrLf & "    Current search in:(XTF_Topics" & WordCount & ".brn)" & VbCrLf
      TempTopic = HalBrain.TopicSearch(TestSentence, WorkingDir & "XTF_Topics" & WordCount & ".brn")
      TempTopicArray = Split(TempTopic, ",", 2, vbTextCompare)
      If (IsArray(TempTopicArray) = True And UBound(TempTopicArray) = 1) Then
         TempTopic1 = Trim(TempTopicArray(1))
         'If the UserSentence contains a phrase pointing to the same topic as PrevTopic then stay on that topic.
         If (TempTopic1 <> "" And TempTopic1 = PrevTopic) Then
            CurrTopic = PrevTopic
            SameTopic = True
DebugText = DebugText & VbCrLf & "2b) Multiword phrase topic matches PrevTopic. CurrTopic set to PrevTopic:(" & PrevTopic & ")  Searching multiword phrases (" & WordCount & ") words long." & VbCrLf
            Exit For
         End If
         If TempTopic1 <> "" Then
            CurrTopic = TempTopic1  'Save any topic found as CurrTopic, last one found is used as CurrTopic.
DebugText = DebugText & "    *** Multiword topic found:(" & Trim(TempTopicArray(0)) & "), so CurrTopic set to: (" & CurrTopic & ")" & VbCrLf
         End If
      End If
   Next

   'Search all single word topics in the XTF_Topics1.brn for the one that matches the PrevTopic.
   'This allows Hal to pick a relevant topic, not just the first topic he finds. 
   'If the PrevTopic can't be matched then use the last topic found as CurrTopic.
   If SameTopic = False Then  'PrevTopic not matched in prior attempt.
      TempSentence = TestSentence  'Create TempSentence which will get permanently modified by the following procedure.
      For Count = 1 To 10  'Search for up to 10 matches hoping to find a match to PrevTopic.
         TempTopic = HalBrain.TopicSearch(TempSentence, WorkingDir & "XTF_Topics1.brn")
         TempTopicArray = Split(TempTopic, ",", 2, vbTextCompare)
         If (IsArray(TempTopicArray) = True And UBound(TempTopicArray) = 1) Then
            TempWord2 = Trim(TempTopicArray(0))
            TempTopic2 = Trim(TempTopicArray(1))
DebugText = DebugText & VbCrLf & "3a) Search for single word topics that match PrevTopic:(" & PrevTopic & ")" & VbCrLf & "    TestSentence:(" & TempSentence & ")"
DebugText = DebugText & VbCrLf & "    Single word topic found:(" & TempTopic2 & ")  Count:(" & Count & ") topics found thus far." & VbCrLf  
            If (TempTopic2 <> "" And TempTopic2 = PrevTopic) Then
               CurrTopic = PrevTopic
               SameTopic = True
DebugText = DebugText & VbCrLf & "3b) Single word topic matches PrevTopic after (" & Count & ") potential topic(s) found." & VbCrLf & "    CurrTopic set to PrevTopic:(" & PrevTopic & ")" & VbCrLf
               Exit For
            End If
            If (TempTopic2 <> "" And TempTopic1 = "") Then
               CurrTopic = TempTopic2  'If it exists use TempTopic1 preferentially over TempTopic2.
DebugText = DebugText & "    *** Single word topic found, no multiword topic previously found, so CurrTopic set to: (" & CurrTopic & ")" & VbCrLf
            End If
            'Remove last found topic word from TempSentence and search for next topic word.
            TempSentence = Replace(TempSentence, TempWord2, "", 1, -1, vbTextCompare)
         End If
      Next
   End If

   'Search PrevTopic "related" topics file for a match. If at least one related topic word in UserSentence
   'exists then assume user has not changed topics and set CurrTopic to PrevTopic.
   'Example:
   '1) "The beach is nice." BaseTopicSingular = "BEACH", PrevTopic = "", CurrTopic = "BEACH".
   '2) "The sand at the beach is smooth." BaseTopicSingular = "SAND", PrevTopic = "BEACH", PrevTopic is found in UserSentence thus
   '   CurrTopic becomes "BEACH". Since (CurrTopic = PrevTopic) <> (BaseTopicSingular), Hal asks the user if "SAND" and "BEACH" are related.
   '   If the user answers "Yes" then "SAND" is added to "XTF_BEACH_Related.brn" to denote that "SAND" And "BEACH" are related.
   '   Also "BEACH" is added to "XTF_SAND_Related.brn" for the same reason.
   '3) "The sand is nice." BaseTopicSingular = "SAND", PrevTopic = "BEACH".
   '   A check of "XTF_BEACH_Related.brn" reveals "SAND" is related to the PrevTopic "BEACH" thus CurrTopic becomes "BEACH".
   If (SameTopic = False And PrevTopic <> "") Then
      If HalBrain.TopicSearch(" " & UserSentence & " ", WorkingDir & "XTF_" & Trim(PrevTopic) & "_Related.brn") = "True" Then
         CurrTopic = PrevTopic
         SameTopic = True
DebugText = DebugText & VbCrLf & "4)  A ""related"" topic word was found in UserSentence that is related to PrevTopic. CurrTopic set to PrevTopic:(" & PrevTopic & ")" & VbCrLf
      End If
   End If

   'If a topic match to PrevTopic wasn't found then use BaseTopicSingular, if it exists, as CurrTopic.
   'If BaseTopicSingular doesn't exist then use any general topic identified and saved as CurrTopic above 
   'as the CurrTopic and assume the user has changed the topic.
   If (SameTopic = False And BaseTopicSingular <> "") Then   
      CurrTopic = BaseTopicSingular
DebugText = DebugText & VbCrLf & "5)  No match to PrevTopic was found. CurrTopic set to BaseTopicSingular:(" & BaseTopicSingular & ")" & VbCrLf
   End If 

   'If no topic identified yet and PrevTopic exists, use PrevTopic once.
   If (SameTopic = False And CurrTopic = "" And PrevTopic <> "") Then
      'If no CurrTopic has been found then use PrevTopic once as CurrTopic. It probably is related enough for
      'a discussion, but block the saving of any QA data to brn file.
      CurrTopic = PrevTopic
      PrevTopic = ""  'Reset PrevTopic since we use it just once.
      BlockPrevTopicSave = True  'Block saving to the PrevTopic since we didn't really find a valid topic.
      BlockTopicSave = True  'We can't be sure Hal is on topic so don't save current UserSentence to QA brn files.
DebugText = DebugText & VbCrLf & "6)  No match to PrevTopic was found. CurrTopic set to PrevTopic:(" & PrevTopic & ")" & VbCrLf
   End If
DebugText = DebugText & VbCrLf & "7)  Final CurrTopic is:(" & CurrTopic & ")" & VbCrLf

'Note: At the end of this routine; 1) Hal is sticking with the PrevTopic, 2) using BaseTopicSingular derived from the Subject as a
'  topic, 3) has found a new general topic in UserSentence, or 4) hasn't found anything to use as CurrTopic so uses PrevTopic one
'  time if it exists.
End If
DebugText =  DebugText & VbCrLf & "END ---------- SEARCH FOR PREVTOPIC MATCH --------- END" & VbCrLf & VbCrLf


'QA BRAIN SEARCH:
'If CurrTopic exists then create a GetResponse.
NotRepeat = True
DebugText = DebugText & VbCrLf & "START ============= QA BRAIN SEARCH ============= START" & VbCrLf
DebugText = DebugText & VbCrLf & "0)  CurrTopic:(" & CurrTopic & ")  GetResponseBlock:(" & GetResponseBlock & ")  TempPrevTopic:(" & TempPrevTopic & ")"
DebugText = DebugText & VbCrLf & "    If ((CurrTopic <> """" And GetResponseBlock <> True) Or TempPrevTopic <> """") then run." & VbCrLf
If ((CurrTopic <> "" And GetResponseBlock <> True) Or TempPrevTopic <> "") Then  'If CurrTopic exists the get a response.
   If TempPrevTopic <> "" Then
      XTF_Response1 = HalBrain.QABrain(PrevUserSent, WorkingDir & Trim(UserName) & "usersent.brn", XTF_UserBrainRel1)
      XTF_Response2 = HalBrain.QABrain(PrevUserSent, WorkingDir & "XTF_" & Trim(TempPrevTopic) & "(" & Trim(UserName) & ").brn", XTF_UserBrainRel2)
DebugText = DebugText & VbCrLf & "1a) TempPrevTopic response. PrevUserSent:(" & PrevUserSent & ")" & VbCrLf & "    From QA file:(" & Trim(UserName) & "usersent.brn)" & VbCrLf & "    XTF_Response1:(" & XTF_Response1 & ")  XTF_UserBrainRel1:(" & XTF_UserBrainRel1 & ")" & VbCrLf
DebugText = DebugText & VbCrLf & "    TempPrevTopic response. PrevUserSent:(" & PrevUserSent & ")" & VbCrLf & "    From QA file:(XTF_" & Trim(TempPrevTopic) & "(" & Trim(UserName) & ").brn)" & VbCrLf & "    XTF_Response2:(" & XTF_Response2 & ")  XTF_UserBrainRel2:(" & XTF_UserBrainRel2 & ")" & VbCrLf
   Else
      XTF_Response1 = HalBrain.QABrain(UserSentence, WorkingDir & "XTF_" & Trim(CurrTopic) & "(" & Trim(UserName) & ").brn", XTF_UserBrainRel1)
      XTF_Response2 = HalBrain.QABrain(UserSentence, WorkingDir & "XTF_" & Trim(CurrTopic) & "_AllUsers.brn", XTF_UserBrainRel2)
DebugText = DebugText & VbCrLf & "1b) Non-TempPrevTopic response. CurrTopic:(" & CurrTopic & ")" & VbCrLf & "    From QA file:(XTF_" & Trim(CurrTopic) & "(" & Trim(UserName) & ").brn)" & VbCrLf & "    XTF_Response1:(" & XTF_Response1 & ")  XTF_UserBrainRel1:(" & XTF_UserBrainRel1 & ")" & VbCrLf
DebugText = DebugText & VbCrLf & "    Non-TempPrevTopic response. CurrTopic:(" & CurrTopic & ")" & VbCrLf & "    From QA file:(XTF_" & Trim(CurrTopic) & "_AllUsers.brn)" & VbCrLf & "    XTF_Response2:(" & XTF_Response2 & ")  XTF_UserBrainRel2:(" & XTF_UserBrainRel2 & ")" & VbCrLf
   End If
   
   'Choose the best response from either the user specific QA file or the "AllUsers" shared QA file.
   If XTF_UserBrainRel1 >= XTF_UserBrainRel2 Then  
      XTF_Response = XTF_Response1
      XTF_UserBrainRel = XTF_UserBrainRel1
DebugText = DebugText & VbCrLf & "2a) Use XTF_Response1 response." & VbCrLf
   Else
      XTF_Response = XTF_Response2
      XTF_UserBrainRel = XTF_UserBrainRel2
DebugText = DebugText & VbCrLf & "2b) Use XTF_Response2 response." & VbCrLf
   End If

DebugText = DebugText & VbCrLf & "3)  CurrTopic:(" & CurrTopic & ")  TempPrevTopic:(" & TempPrevTopic & ")"
DebugText = DebugText & VbCrLf & "    XTF_Response:(" & XTF_Response & ")  XTF_UserBrainRel:(" & XTF_UserBrainRel & ")"
DebugText = DebugText & VbCrLf & "    If XTF_UserBrainRel > 12 and < 25 there is only a 50% chance the response will be used." & VbCrLf

   'Use responses with scores > 25 everytime, use marginal responses 50% of the time, and never use responses with scores < 13.
   If ((XTF_UserBrainRel > 12 And Int(Rnd * 100) < 50) Or (XTF_UserBrainRel > 25)) Then 
     'We check to see if Hal is going to repeat himself.
      If HalBrain.CheckRepetition(UCase(Trim(XTF_Response)), UCase(Trim(UserSentence))) = True Then NotRepeat = False 
      If HalBrain.CheckRepetition(UCase(Trim(XTF_Response)), UCase(Trim(PrevSent))) = True Then NotRepeat = False 
      If HalBrain.CheckRepetition(UCase(Trim(XTF_Response)), UCase(Trim(PrevUserSent))) = True Then NotRepeat = False 
      'If a response wasn't found previously, and other conditions are met, we make GetResponse equal to what we found.
DebugText = DebugText & VbCrLf & "4)  XTF_Response:(" & XTF_Response & ")" & VbCrLf & "    XTF_UserBrainRel:(" & XTF_UserBrainRel & ")  NotRepeat:(" & NotRepeat & ")  If NotRepeat = False then don't use response." & VbCrLf
      If NotRepeat = True Then
         GetResponse = GetResponse & XTF_Response & "." & VbCrLf
         DebugText = DebugText & VbCrLf & "5)  A response of relevance (" & XTF_UserBrainRel & ") was found in the (XTF_" & Trim(CurrTopic) & "(" & Trim(UserName) & ").brn) focus file and this response has been used."
         DebugInfo = DebugInfo & VbCrLf & "A response of relevance (" & XTF_UserBrainRel & ") was found in the (XTF_" & Trim(CurrTopic) & "(" & Trim(UserName) & ").brn) focus file and this response has been used."
      End If
   End If
End If
DebugText =  DebugText & VbCrLf & "END --------------- QA BRAIN SEARCH --------------- END" & VbCrLf & VbCrLf


'WRITE TOPICS FOUND TO FILES:
'Check if the topic already exists before writing to topic files.
'Write topics to 1 or more of 4 main topic files.
DebugText =  DebugText & VbCrLf & "START ======= WRITE TOPICS FOUND TO FILES ======= START" & VbCrLf
DebugText = DebugText & VbCrLf & "0)  BaseTopicSingular:(" & BaseTopicSingular & ")  BlockSave:(" & BlockSave & ")"
DebugText = DebugText & VbCrLf & "    If (BaseTopicSingular <> """" And BlockSave <> True) then run." 
DebugText = DebugText & VbCrLf & "    Topics are only written into a file if they don't already exist." & VbCrLf 
If BaseTopicSingular <> "" And BlockSave <> True Then 
   If (DetailTopicPlural <> "" And DetailTopicPlural <> DetailTopicSingular) Then  'Write DetailTopicPlural to file.
      WordCount = 1 + HalBrain.CountInstances(" ", Trim(DetailTopicPlural))  'WordCount should already be limited to 4 words max.
      If HalBrain.TopicSearch(DetailTopicPlural, WorkingDir & "XTF_Topics" & WordCount & ".brn") = "" Then
         HalBrain.AppendFile WorkingDir & "XTF_Topics" & WordCount & ".brn", """" & " " & Trim(DetailTopicPlural) & " " & """,""" & Trim(DetailTopicPlural) & "," & Trim(BaseTopicSingular) & """"
DebugText = DebugText & VbCrLf & "1)  Write DetailTopicPlural to file. DetailTopicPlural:(" & DetailTopicPlural & ")" & VbCrLf
      End If
   End If

   If DetailTopicSingular <> "" Then  'Write DetailTopicSingular to file.
      WordCount = 1 + HalBrain.CountInstances(" ", Trim(DetailTopicSingular))  'WordCount should already be limited to 4 words max.
      If HalBrain.TopicSearch(DetailTopicSingular, WorkingDir & "XTF_Topics" & WordCount & ".brn") = "" Then
         HalBrain.AppendFile WorkingDir & "XTF_Topics" & WordCount & ".brn", """" & " " & Trim(DetailTopicSingular) & " " & """,""" & Trim(DetailTopicSingular) & "," & Trim(BaseTopicSingular) & """"
DebugText = DebugText & VbCrLf & "2)  Write DetailTopicSingular to file. DetailTopicSingular:(" & DetailTopicSingular & ")" & VbCrLf
      End If 
   End If

   If (BaseTopicPlural <> "" And BaseTopicPlural <> BaseTopicSingular) Then  'Write BaseTopicPlural to file.
      If HalBrain.TopicSearch(BaseTopicPlural, WorkingDir & "XTF_Topics1.brn") = "" Then
         HalBrain.AppendFile WorkingDir & "XTF_Topics1.brn", """" & " " & Trim(BaseTopicPlural) & " " & """,""" & Trim(BaseTopicPlural) & "," & Trim(BaseTopicSingular) & """"
DebugText = DebugText & VbCrLf & "3)  Write BaseTopicPlural to file. BaseTopicPlural:(" & BaseTopicPlural & ")" & VbCrLf
      End If
   End If

   If BaseTopicSingular <> "" Then  'Write BaseTopicSingular to file.
      If HalBrain.TopicSearch(BaseTopicSingular, WorkingDir & "XTF_Topics1.brn") = "" Then
         HalBrain.AppendFile WorkingDir & "XTF_Topics1.brn", """" & " " & Trim(BaseTopicSingular) & " " & """,""" & Trim(BaseTopicSingular) & "," & Trim(BaseTopicSingular) & """"
DebugText = DebugText & VbCrLf & "4)  Write BaseTopicSingular to file. BaseTopicSingular:(" & BaseTopicSingular & ")" & VbCrLf
      End If
   End If

   'Create a 'related' topics file containing meronyms as related topic words if one doesn't already exist.
   If HalBrain.TopicSearch("[MERONYMS_EXIST_FLAG]", WorkingDir & "XTF_" & Trim(BaseTopicSingular) & "_Related.brn") <> "True" Then
      Dim RelTopicArray1
      RelTopicWords = ""
      'Search for meronyms. Look for up to 5 senses of meronyms.
      WN.LookUpWord(BaseTopicSingular)  'Meronyms are "parts of" another thing.
      For X = 1 To 5
         GetWords = WN.GetMeronyms(X) 
         If GetWords <> "" Then RelTopicWords = RelTopicWords & ", " & GetWords
      Next
      'Extract meronyms from list, format, and write to file.
      If RelTopicWords <> "" Then
         RelTopicWords = Replace(RelTopicWords, ",", "", 1, 1, vbTextCompare)  'Remove leading ","
         RelTopicWords = Replace(RelTopicWords, "(", "", 1, -1, vbTextCompare)
         RelTopicWords = Replace(RelTopicWords, ")", "", 1, -1, vbTextCompare)
         RelTopicWords = Trim(UCase(RelTopicWords))
         RelTopicArray1 = Split(RelTopicWords, ",", -1, vbTextCompare)
         If (IsArray(RelTopicArray1) = True And UBound(RelTopicArray1) > -1) Then  'Write meronyms to 'related' file.
            RelMeronyms = """" & " " & "[MERONYMS_EXIST_FLAG]" & " " & """,""" & "True" & """" & VbCrLf
            For X = 0 To UBound(RelTopicArray1)
               RelMeronyms = RelMeronyms & """" & " " & Trim(RelTopicArray1(X)) & " " & """,""" & "True" & """" & VbCrLf
            Next
            RelMeronyms = RelMeronyms & """" & " " & "[MERONYMS_END_HERE]" & " " & """,""" & "True" & """"
            HalBrain.AppendFile WorkingDir & "XTF_" & Trim(BaseTopicSingular) & "_Related.brn", RelMeronyms
DebugText = DebugText & VbCrLf & "5)  Related meronyms written to file:(XTF_" & Trim(BaseTopicSingular) & "_Related.brn)" & VbCrLf
         End If
      End If
   End If

   'Create a 'related' topics file containing synonyms as related topic words if one doesn't already exist.
   If HalBrain.TopicSearch("[SYNONYMS_EXIST_FLAG]", WorkingDir & "XTF_" & Trim(BaseTopicSingular) & "_Related.brn") <> "True" Then
      Dim RelTopicArray2
      RelTopicWords = ""
      'Search for synonyms. Look for up to 5 senses of synonyms.
      WN.LookUpWord(BaseTopicSingular)  'Synonyms have identical meanings.
      For X = 1 To 5
         GetWords = WN.GetSynonyms("NOUN", X)
         If GetWords <> "" Then RelTopicWords = RelTopicWords & ", " & GetWords
      Next
      'Extract synonyms from list, format, and write to file.
      If RelTopicWords <> "" Then
         RelTopicWords = Replace(RelTopicWords, ",", "", 1, 1, vbTextCompare)  'Remove leading ","
         RelTopicWords = Replace(RelTopicWords, "(", "", 1, -1, vbTextCompare)
         RelTopicWords = Replace(RelTopicWords, ")", "", 1, -1, vbTextCompare)
         RelTopicWords = Trim(UCase(RelTopicWords))
         RelTopicArray2 = Split(RelTopicWords, ", ", -1, vbTextCompare)
         If (IsArray(RelTopicArray2) = True And UBound(RelTopicArray2) > -1) Then  'Write synonyms to 'related' file.
            RelSynonyms = """" & " " & "[SYNONYMS_EXIST_FLAG]" & " " & """,""" & "True" & """" & VbCrLf
            For X = 0 To UBound(RelTopicArray2)
               RelSynonyms = RelSynonyms & """" & " " & Trim(RelTopicArray2(X)) & " " & """,""" & "True" & """" & VbCrLf
            Next
            RelSynonyms = RelSynonyms & """" & " " & "[SYNONYMS_END_HERE]" & " " & """,""" & "True" & """"
            HalBrain.AppendFile WorkingDir & "XTF_" & Trim(BaseTopicSingular) & "_Related.brn", RelSynonyms
DebugText = DebugText & "6)  Related synonyms written to file:(XTF_" & Trim(BaseTopicSingular) & "_Related.brn)" & VbCrLf
         End If
      End If
   End If
End If
DebugText =  DebugText & VbCrLf & "END --------- WRITE TOPICS FOUND TO FILES --------- END" & VbCrLf & VbCrLf


'CREATE RELATED TOPICS INQUIRY:
'Save data to 'related' topic files. If any word in the UserSentence matches one from the 'related' topic file for
'the PrevTopic then Hal assumes that the user has not changed the topic.
DebugText = DebugText & VbCrLf & VbCrLf & "START ====== CREATE RELATED TOPICS INQUIRY ====== START" & VbCrLf
DebugText = DebugText & VbCrLf & "0)  BaseTopicSingular:(" & BaseTopicSingular & ")  CurrTopic:(" & CurrTopic & ")  PrevTopic:(" & PrevTopic & ")"
DebugText = DebugText & VbCrLf & "    If BaseTopicSingular is a pronoun or other poor Subject then don't run."
DebugText = DebugText & VbCrLf & "    If (BaseTopicSingular <> """" And BaseTopicSingular <> CurrTopic And CurrTopic = PrevTopic) then run." & VbCrLf
PoorSubject = False

If HalBrain.TopicSearch(" " & BaseTopicSingular & " ", WorkingDir & "XTF_SYS_PoorSubjectWords.brn") <> "" Then PoorSubject = True
If (BaseTopicSingular <> "" And BaseTopicSingular <> CurrTopic And SameTopic = True And PoorSubject <> True And LearningLevel > 0) And GetResponseBlock <> True Then  'BaseTopicSingular and CurrTopic are related topics. Write to related topics file.
   'BaseTopicSingular and CurrTopic are related topics. Write to related topics file.
   'Pronouns and poor Subject words are excluded from related topics.
   RelProceed = False
   TFStatus1 = ""

   If PrevTopic <> "" Then
      TFStatus1 = HalBrain.TopicSearch(PrevTopic, WorkingDir & "XTF_" & Trim(BaseTopicSingular) & "_Related.brn")
      If TFStatus1 = "" Then RelProceed = True 
DebugText = DebugText & VbCrLf & "1)  PrevTopic:(" & PrevTopic & ")"
DebugText = DebugText & VbCrLf & "    TFStatus1:(" & TFStatus1 & ")" & "  RelProceed:(" & RelProceed & ")" & VbCrLf
   End If

   If PrevTopicPlural <> "" And RelProceed = False Then
      TFStatus1 = HalBrain.TopicSearch(PrevTopicPlural, WorkingDir & "XTF_" & Trim(BaseTopicSingular) & "_Related.brn")
      If TFStatus1 = "" Then RelProceed = True 
DebugText = DebugText & VbCrLf & "2)  PrevTopicPlural:(" & PrevTopicPlural & ")"
DebugText = DebugText & VbCrLf & "    TFStatus1:(" & TFStatus1 & ")" & "  RelProceed:(" & RelProceed & ")" & VbCrLf
   End If
   
   If BaseTopicSingular <> "" And RelProceed = False Then   
      TFStatus1 = HalBrain.TopicSearch(BaseTopicSingular, WorkingDir & "XTF_" & Trim(PrevTopic) & "_Related.brn")
      If TFStatus1 = "" Then RelProceed = True
DebugText = DebugText & VbCrLf & "3)  BaseTopicSingular:(" & BaseTopicSingular & ")"
DebugText = DebugText & VbCrLf & "    TFStatus1:(" & TFStatus1 & ")" & "  RelProceed:(" & RelProceed & ")" & VbCrLf
   End If

   If BaseTopicPlural <> "" And RelProceed = False Then
      TFStatus1 = HalBrain.TopicSearch(BaseTopicPlural, WorkingDir & "XTF_" & Trim(PrevTopic) & "_Related.brn")
      If TFStatus1 = "" Then RelProceed = True
DebugText = DebugText & VbCrLf & "4)  BaseTopicPlural:(" & BaseTopicPlural & ")"
DebugText = DebugText & VbCrLf & "    TFStatus1:(" & TFStatus1 & ")" & "  RelProceed:(" & RelProceed & ")" & VbCrLf
   End If
 
   'If RelProceed is true then create inquiry to user and ask if topics are related.
   'Even if RelProceed is false Hal can still inquire randomly depending on the 
   'LearningLevel. This allows the user to "undo" or provide a different answer than
   'provided previously.
   SpinMultiplier = 15
   LearningLevelMax = 50
   Spinner = Int(Rnd * LearningLevelMax * SpinMultiplier)
DebugText = DebugText & VbCrLf & "8)  RelProceed:(" & RelProceed & ")  Spinner:(" & Spinner & ")  LearningLevel [max = 50]:(" & LearningLevel & ")  BaseTopicSingular:(" & BaseTopicSingular & ")"
DebugText = DebugText & VbCrLf & "    If ((RelProceed = True Or Spinner < LearningLevel [max = 50]) And BaseTopicSingular <> """") then run." & VbCrLf
   If ((RelProceed = True Or Spinner < LearningLevel) And Spinner < (LearningLevel * SpinMultiplier) And BaseTopicSingular <> "") Then
      RelPrevTopic = PrevTopic
      RelPrevTopicPlural = PrevTopicPlural                                  
      RelDetailTopicPlural = DetailTopicPlural                                                       
      RelDetailTopicSingular = DetailTopicSingular   
      RelBaseTopicPlural = BaseTopicPlural
      RelBaseTopicSingular = BaseTopicSingular   
DebugText = DebugText & VbCrLf & "9)  RelPrevTopic:(" & RelPrevTopic & ")" & VbCrLf & "    RelPrevTopicPlural:(" & RelPrevTopicPlural & ")" & VbCrLf & "    RelDetailTopicPlural:(" & RelDetailTopicPlural & ")" & VbCrLf & "    RelDetailTopicSingular:(" & RelDetailTopicSingular & ")"
DebugText = DebugText & VbCrLf & "    RelBaseTopicPlural:(" & RelBaseTopicPlural & ")" & VbCrLf & "    RelBaseTopicSingular:(" & RelBaseTopicSingular & ")" & VbCrLf

      Select Case Int(Rnd * 4) + 1
         Case 1 
            GetResponse = "Question. Are <quote>" & RelPrevTopic & "<quote> and <quote>" & BaseTopicSingular & "<quote> related topics?"
         Case 2
            GetResponse = "Should I consider <quote>" & RelPrevTopic & "<quote> and <quote>" & BaseTopicSingular & "<quote> related topics?"
         Case 3
            GetResponse = "Are <quote>" & RelPrevTopic & "<quote> and <quote>" & BaseTopicSingular & "<quote> part of the same topic?"
         Case 4
            GetResponse = "Are <quote>" & RelPrevTopic & "<quote> and <quote>" & BaseTopicSingular & "<quote> related topics?"
      End Select
      QuestionPending = "CREATE RELATED TOPICS"  'Triggers the "CREATE RELATED TOPICS RESPONSE" Function.
DebugText = DebugText & VbCrLf & "10) The user was asked:(" & GetResponse & ")" & VbCrLf & "QuestionPending flag is set to:(" & QuestionPending & ")" & VbCrLf
   Else
DebugText = DebugText & VbCrLf & "10) Hal decided not to ask the user if two topics are related." & VbCrLf
   End If
End If
DebugText = DebugText & VbCrLf & "END -------- CREATE RELATED TOPICS INQUIRY -------- END" & VbCrLf & VbCrLf
                                 

'WRITE NEW QA DATA TO FILES:                   
'If BaseTopicSingular exists then write QA info to the BaseTopicSingular brn file.
'If BaseTopicSingular doesn't exist, but CurrTopic does then write the same QA info to the CurrTopic brn file.
DebugText = DebugText & VbCrLf & VbCrLf & "START ======= WRITE NEW QA DATA TO FILES ======== START" & VbCrLf
DebugText = DebugText & VbCrLf & "0)  BaseTopicSingular:(" & BaseTopicSingular & ")  BlockTopicSave:(" & BlockTopicSave & ")  BlockSave:(" & BlockSave & ")  LearningLevel:(" & LearningLevel & ")"
DebugText = DebugText & VbCrLf & "    If (BaseTopicSingular <> """" And BlockTopicSave = False And BlockSave <> True And LearningLevel > 1) then run."
DebugText = DebugText & VbCrLf & "    Current QA data is only written into a file if it doesn't already exist." & VbCrLf

If (BaseTopicSingular <> "" And BlockTopicSave = False And BlockSave <> True And LearningLevel > 1) Then  'Write QA data to brn file.
   AnswerSent = "@" & Trim(UserSentence)
   'QuestionSent = " " & Trim(HalBrain.ExtractKeywords(UserSentence)) & " "
   QuestionSent = " " & HalBrain.AlphaNumericalOnly(Trim(HalBrain.ExtractKeywords(UserSentence))) & " " 'Try removing punctuation from keywords. Does this make for a better match?

   'Test to see if an exact QA response already exists. If so, try not to write it to the file again.
   HalUserBrain = HalBrain.QABrain(QuestionSent, WorkingDir & "XTF_" & Trim(BaseTopicSingular) & "(" & Trim(UserName) & ").brn", TestRel)
   If HalBrain.CountInstances(" ", QuestionSent) > 2 And Len(AnswerSent) > 8 And Len(QuestionSent) > 9 And InStr(1, AnswerSent, " ", vbTextCompare) > 0 And TestRel < 75 Then
      If LearningLevel > 1 Then HalBrain.AppendFile WorkingDir & "XTF_" & Trim(BaseTopicSingular) & "(" & Trim(UserName) & ").brn", AnswerSent & VbCrLf & QuestionSent
DebugText = DebugText & VbCrLf & "1)  If it doesn't exist already write current user QA data into file:(XTF_" & Trim(BaseTopicSingular) & "(" & Trim(UserName) & ").brn)" & VbCrLf
   End If

   'If there are no pronouns in the UserSentence then save the QA info to the "all users" shared QA files.
   If HalBrain.TopicSearch(UserSentence, WorkingDir & "XTF_SYS_NotUserPronounDetect.brn") = "" Then
      'Test to see if an exact QA response already exists. If so, try not to write it to the file again.
      HalUserBrain = HalBrain.QABrain(QuestionSent, WorkingDir & "XTF_" & Trim(BaseTopicSingular) & "_AllUsers.brn", TestRel)
      If HalBrain.CountInstances(" ", QuestionSent) > 2 And Len(AnswerSent) > 8 And Len(QuestionSent) > 9 And InStr(1, AnswerSent, " ", vbTextCompare) > 0 And TestRel < 75 Then
         If LearningLevel > 1 Then HalBrain.AppendFile WorkingDir & "XTF_" & Trim(BaseTopicSingular) & "_AllUsers.brn", AnswerSent & VbCrLf & QuestionSent
DebugText = DebugText & VbCrLf & "2)  If it doesn't exist already write current generic QA data into file:(XTF_" & Trim(BaseTopicSingular) & "_AllUsers.brn)" & VbCrLf
      End If
   End If
End If

If (SameTopic = True And CurrTopic <> "" And BlockTopicSave = False And BlockSave <> True And LearningLevel > 1) Then  'Write the same QA info for CurrTopic.
   AnswerSent = "@" & Trim(UserSentence)
   'QuestionSent = " " & Trim(HalBrain.ExtractKeywords(UserSentence)) & " "
   QuestionSent = " " & HalBrain.AlphaNumericalOnly(Trim(HalBrain.ExtractKeywords(UserSentence))) & " " 'Try removing punctuation from keywords. Does this make for a better match?

   'Test to see if an exact QA response already exists. If so, try not to write it to the file again.
   HalUserBrain = HalBrain.QABrain(QuestionSent, WorkingDir & "XTF_" & Trim(CurrTopic) & "(" & Trim(UserName) & ").brn", TestRel)
   If HalBrain.CountInstances(" ", QuestionSent) > 2 And Len(AnswerSent) > 8 And Len(QuestionSent) > 9 And InStr(1, AnswerSent, " ", vbTextCompare) > 0 And TestRel < 75 Then
      If LearningLevel > 1 Then HalBrain.AppendFile WorkingDir & "XTF_" & Trim(CurrTopic) & "(" & Trim(UserName) & ").brn", AnswerSent & VbCrLf & QuestionSent
DebugText = DebugText & VbCrLf & "3)  If it doesn't exist already write current user QA data into file:(XTF_" & Trim(CurrTopic) & "(" & Trim(UserName) & ").brn)" & VbCrLf
   End If

   'If there are no pronouns in the UserSentence then save the QA info to the "all users" shared QA files.
   If HalBrain.TopicSearch(UserSentence, WorkingDir & "XTF_SYS_PronounDetect.brn") = "" Then
      'Test to see if an exact QA response already exists. If so, try not to write it to the file again.
      HalUserBrain = HalBrain.QABrain(QuestionSent, WorkingDir & "XTF_" & Trim(CurrTopic) & "_AllUsers.brn", TestRel)
      If HalBrain.CountInstances(" ", QuestionSent) > 2 And Len(AnswerSent) > 8 And Len(QuestionSent) > 9 And InStr(1, AnswerSent, " ", vbTextCompare) > 0 And TestRel < 75 Then
         If LearningLevel > 1 Then HalBrain.AppendFile WorkingDir & "XTF_" & Trim(CurrTopic) & "_AllUsers.brn", AnswerSent & VbCrLf & QuestionSent
DebugText = DebugText & VbCrLf & "4)  If it doesn't exist already write current generic QA data into file:(XTF_" & Trim(CurrTopic) & "_AllUsers.brn)" & VbCrLf
      End If
   End If
End If
DebugText = DebugText & VbCrLf & "END --------- WRITE NEW QA DATA TO FILES ---------- END" & VbCrLf & VbCrLf


'PRESERVE VARIABLES:
'Preserve CurrTopic for XTF topic function use on next cycle.
DebugText = DebugText & VbCrLf & VbCrLf & "START ============ PRESERVE VARIABLES ============ START" & VbCrLf
DebugText = DebugText & VbCrLf & "0)  BlockPrevTopicSave:(" & BlockPrevTopicSave & ")  CurrTopic:(" & CurrTopic & ")  PrevTopic:(" & PrevTopic & ")  BaseTopicSingular:(" & BaseTopicSingular & ")"
DebugText = DebugText & VbCrLf & "    If (BlockPrevTopicSave <> True) then run." & VbCrLf
PrevTopicPlural = ""  'Reset PrevTopicPlural
If BlockPrevTopicSave <> True Then                                           
   PrevTopic = Trim(CurrTopic)
   'If possible create a PrevTopicPlural to enhance the related topics function.
   If (CurrTopic = BaseTopicSingular And BaseTopicSingular <> "") Then
      PrevTopicPlural = Trim(BaseTopicPlural)
   End If
DebugText = DebugText & VbCrLf & "1)  BlockPrevTopicSave:(" & BlockPrevTopicSave & ")  Time to preserve some variables for next time."
DebugText = DebugText & VbCrLf & "    PrevTopic:(" & PrevTopic & ")   BaseTopicSingular:(" & BaseTopicSingular & ")"
DebugText = DebugText & VbCrLf & "    PrevTopicPlural:(" & PrevTopicPlural & ")   BaseTopicPlural:(" & BaseTopicPlural & ")"
DebugText = DebugText & VbCrLf & "    CurrTopic = BaseTopicSingular therefore PrevTopicPlural = BaseTopicPlural" & VbCrLf
End If                                                      
DebugText = DebugText & VbCrLf & VbCrLf & "END ------------- PRESERVE VARIABLES -------------- END" & VbCrLf

'WRITE FINAL DEBUG INFO TO LOG:
DebugText = DebugText & VbCrLf & "END ================ XTF DEBUG LOG ================ END"
DebugText = DebugText & VbCrLf & "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" & VbCrLf & VbCrLf & VbCrLf
'HalBrain.AppendFile WorkingDir & "Z_XTF_DEBUG_LOG.TXT", DebugText
'DebugText = ""
'DEBUG LOG END
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


'RESPOND: RESPOND BY PARAPHRASING THE USER WHEN "IS" OR "ARE" ARE FOUND
	'This code section shows how strings can be split 
    'into arrays and used "live" within the script by Hal.
	'This strategy can allow Hal to make many clever 
    'paraphrases of all sorts of sentences, with unlimited 
	'unpredictable variety. 
    Paraphrase = ""
	If Len(GetResponse) < 4 And InStr(UserSentence, " IS ") > 0 And HalBrain.CheckLinkingVerb(UserSentence) = True And HalBrain.TopicSearch(UserSentence, WorkingDir & "disqualify5.brn") <> "True" Then
'ORIG:	If InStr(UserSentence, " IS ") > 0 And HalBrain.CheckLinkingVerb(UserSentence) = True And HalBrain.TopicSearch(UserSentence, WorkingDir & "disqualify5.brn") <> "True" Then
		SentPieces = Split(UserSentence, " is ", 2, vbTextCompare)
		SubPhrase = Trim(SentPieces(0))
		PredPhrase = Trim(SentPieces(1))
		'Here we only use the array elements for a response if the
		'subject and predicate contain few words, hence few spaces:
		If HalBrain.CountInstances(" ", SubPhrase) < 4 Then SubGood = True
		If Len(SubPhrase) < 3 Then SubGood = False
		If HalBrain.CountInstances(" ", PredPhrase) < 4 Then PredGood = True
		If Len(PredPhrase) < 3 Then PredGood = False
		If SubGood = True And PredGood = True Then 
			Paraphrase = HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_paraphrase-is.brn")
			Paraphrase = Replace(Paraphrase, "<Subject>", SubPhrase, 1, -1, vbTextCompare)
			Paraphrase = Replace(Paraphrase, "<Predicate>", PredPhrase, 1, -1, vbTextCompare)
		End If
	End If
  
    'We make sure the word "ARE" isn't a contraction, 
    'to make sure we can detect it:
	UserSentence = Replace("" & UserSentence & "", "'RE ", " ARE ", 1, -1, vbTextCompare) 
 
    'We repeat the earlier routine, this time for "ARE" sentences:
	If Len(GetResponse) < 4 And InStr(UserSentence, " ARE ") > 0 And Not InStr(UserSentence, " YOU ARE ") > 0 And HalBrain.CheckLinkingVerb(UserSentence) = True And HalBrain.TopicSearch(UserSentence, WorkingDir & "disqualify5.brn") <> "True" Then
'ORIG: If InStr(UserSentence, " ARE ") > 0 And HalBrain.CheckLinkingVerb(UserSentence) = True And HalBrain.TopicSearch(UserSentence, WorkingDir & "disqualify5.brn") <> "True" Then
		SentPieces = Split(UserSentence, " are ", 2, vbTextCompare)
		SubPhrase = Trim(SentPieces(0))
		PredPhrase = Trim(SentPieces(1))
		'Here we only use the array elements for a response if the
		'subject and predicate contain few words, hence few spaces:
		SubGood = False
		PredGood = False
		If HalBrain.CountInstances(" ", SubPhrase) < 4 Then SubGood = True
		If Len(SubPhrase) < 3 Then SubGood = False
		If HalBrain.CountInstances(" ", PredPhrase) < 4 Then PredGood = True
		If Len(PredPhrase) < 3 Then PredGood = False
		If SubGood = True And PredGood = True Then 
			Paraphrase = HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_paraphrase-are.brn")
			Paraphrase = Replace(Paraphrase, "<Subject>", SubPhrase, 1, -1, vbTextCompare)
			Paraphrase = Replace(Paraphrase, "<Predicate>", PredPhrase, 1, -1, vbTextCompare)
		End If
	End If             

'=vonsmith= Added GetResponseBlock
	If Len(Paraphrase) > 4 And GetResponseBlock <> True Then
		If ((Rnd * 100) < 30 And Len(GetResponse) < 4) Then
			GetResponse = Paraphrase
			DebugInfo = DebugInfo & "Hal has responded by paraphrasing the user: " & Paraphrase & VbCrLf
		Else                                                                                
			DebugInfo = DebugInfo & "Hal has thought about paraphrasing the user, but decided not to, for now. The sentence would have been: " & Paraphrase & VbCrLf
		End If
	End If

'=vonsmith= Modify the following to not save duplicate subjects and predicates.	                                        
    'SAVE - If the Subject Phrase is short, we save it for re-use later:
    If SubGood = True And HalBrain.CountInstances(" ", SubPhrase) < 2 And BlockSave <> True Then
    	HalBrain.AppendFile WorkingDir & "random_subject.brn", " " & SubPhrase & " "                                                
    	HalBrain.AppendFile WorkingDir & "assoc_subject.brn", "@" & SubPhrase & VbCrLf & " " & UCase(SubPhrase)
    End If
	                                        
    'SAVE - If the Predicate Phrase is short, we save it for re-use later:
    If PredGood = True And HalBrain.CountInstances(" ", PredPhrase) < 2 And BlockSave <> True Then
    	HalBrain.AppendFile WorkingDir & "random_predicate.brn", " " & PredPhrase & " "                                                
    	HalBrain.AppendFile WorkingDir & "assoc_predicate.brn", "@" & PredPhrase & VbCrLf & " " & UCase(PredPhrase)
    End If

	'RESPOND: ZABAWARE DLL RESPONSES
	'This function from the DLL contains miscellaneous knowledge and simple conversation functions.
	'This was taken from a very early version of Hal, and it is still useful sometimes, especially
	'for responding to short sentences.
	GetResponse = HalBrain.HalFormat(GetResponse)
	If (Len(UserSentence) < 15 And Len(GetResponse) < 4) Or DebugMode = True Then
		OrigBrain = HalBrain.HalFormat(HalBrain.OriginalBrain(OriginalSentence))       		
		If Len(OrigBrain) > 4 And Len(UserSentence) < 15 And Len(GetResponse) < 4 Then 
			GetResponse = GetResponse & " " & OrigBrain & VbCrLf      
			ShortPhrase = ""
			DebugInfo = DebugInfo & "Hal is using the response from the OriginalBrain function: " & OrigBrain & VbCrLf
		ElseIf Len(OrigBrain) > 4 Then
			DebugInfo = DebugInfo & "Hal will not use the response from the OriginalBrain function, which would have been: " & OrigBrain & VbCrLf
			DebugInfo = DebugInfo & GetResponse & VbCrLf	
		End If 
	End If 

	'RESPOND: YES OR NO RESPONSES
	'-vonsmith= This function has been moved toward the top.


	'Main Databases
	'Hal will go through several huge databases to try to find a response
	'The automatic gain control determines whether a particular response will
	'be used or not. The highest relevance response is stored in memory anyway,
	'which might be used if no function in this script is able to respond.
	HighestRel = 0
	HighestRelResponse = ""

 
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'=vonsmith= Function below position swapped with RESPOND: HAL/USER SENTENCE ASSOCIATIONS to give it less precedence.

	'RESPOND: GENERAL USER SENTENCE ASSOCIATIONS
	'If no response is found yet, try a sentence association file collected from the user.
	'This file contains keywords from the user's own sentences associated with those same sentences.
	GetResponse = HalBrain.HalFormat(GetResponse)
	If Len(GetResponse) < 4 Or DebugMode = True Then
		UserBrainRel = 0
		HalUserBrain = HalBrain.QABrain(LongUserSent, WorkingDir & Trim(UserName) & "usersent.brn", UserBrainRel)
		If HalBrain.CheckRepetition(HalUserBrain, UserSentence) = True Or HalBrain.CheckRepetition(HalUserBrain, PrevSent) = True Or HalBrain.CheckRepetition(HalUserBrain, PrevUserSent) = True Then UserBrainRel = 0
		If UserBrainRel > HighestRel Then
			HighestRel = UserBrainRel
			HighestRelResponse = HalUserBrain
		End If
		Score = UserBrainRel + 1
		Hurdle = GainControl + 20 - Int(((Learninglevel - 25) * 0.8)) 'This formula lets the user define the hurdle in Hal's options
		DebugInfo = DebugInfo & "[user]usersent.brn has returned """ & HalUserBrain & """ which had a relevance of " & Score & " which was compared to " & Hurdle & ". "
		If Len(GetResponse) < 4 And Score > Hurdle Then
			GetResponse = GetResponse & " " & HalUserBrain & VbCrLf
'			GetResponse = GetResponse & HalUserBrain & vbCrLf
			DebugInfo = DebugInfo & "Hal has decided to use this sentence." & VbCrLf
		Else
			DebugInfo = DebugInfo & "Hal has decided not to use this sentence." & VbCrLf
		End If
	End If

'=vonsmith= Function above position swapped with RESPOND: HAL/USER SENTENCE ASSOCIATIONS to give it less precedence.
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


	'RESPOND: SHARED USER SENTENCE ASSOCIATIONS
	'If no response is found yet, try a sentence association file
	'whose content seems less likely to be about any specific user.
	GetResponse = HalBrain.HalFormat(GetResponse)
	If Len(GetResponse) < 4 Or DebugMode = True Then
		UserBrainRel = 0
		HalUserBrain = HalBrain.QABrain(LongUserSent, WorkingDir & "shared_usersent.brn", UserBrainRel)
		If HalBrain.CheckRepetition(HalUserBrain, UserSentence) = True Or HalBrain.CheckRepetition(HalUserBrain, PrevSent) = True Or HalBrain.CheckRepetition(HalUserBrain, PrevUserSent) = True Then UserBrainRel = 0
		If UserBrainRel > HighestRel Then
			HighestRel = UserBrainRel
			HighestRelResponse = HalUserBrain
		End If
		Score = UserBrainRel + 1
		Hurdle = GainControl + 20 - Int(((Learninglevel - 25) * 0.8)) 'This formula lets the user define the hurdle in Hal's options
		DebugInfo = DebugInfo & "shared_usersent.brn has returned """ & HalUserBrain & """ which had a relevance of " & Score & " which was compared to " & Hurdle & ". "
		If Len(GetResponse) < 4 And Score > Hurdle Then
			GetResponse = GetResponse & " " & HalUserBrain & VbCrLf
'			GetResponse = GetResponse & HalUserBrain & vbCrLf
			DebugInfo = DebugInfo & "Hal has decided to use this sentence." & VbCrLf
		Else
			DebugInfo = DebugInfo & "Hal has decided not to use this sentence." & VbCrLf
		End If
	End If
 
	'RESPOND: HAL/USER SENTENCE ASSOCIATIONS
	'If no response is found yet, try a general sentence association file
	'generated from a remark by Hal and a response to that remark from the user.
	GetResponse = HalBrain.HalFormat(GetResponse)
	If Learninglevel > 1 And (Len(GetResponse) < 4 Or DebugMode = True) Then
		UserBrainRel = 0
		HalUserBrain = HalBrain.QABrain(LongUserSent, WorkingDir & Trim(UserName) & "convresp.brn", UserBrainRel)
		If HalBrain.CheckRepetition(HalUserBrain, UserSentence) = True Or HalBrain.CheckRepetition(HalUserBrain, PrevSent) = True Or HalBrain.CheckRepetition(HalUserBrain, PrevUserSent) = True Then UserBrainRel = 0
		If UserBrainRel > HighestRel Then
			HighestRel = UserBrainRel
			HighestRelResponse = HalUserBrain
		End If
		Score = UserBrainRel + 1
		Hurdle = GainControl + 20 - Int(((Learninglevel - 25) * 0.8)) 'This formula lets the user define the hurdle in Hal's options
		DebugInfo = DebugInfo & "[user]convresp.brn has returned """ & HalUserBrain & """ which had a relevance of " & Score & " which was compared to " & Hurdle & ". "
		If Len(GetResponse) < 4 And Score > Hurdle Then
			GetResponse = GetResponse & " " & HalUserBrain & VbCrLf
			DebugInfo = DebugInfo & "Hal has decided to use this sentence." & VbCrLf
		Else
			DebugInfo = DebugInfo & "Hal has decided not to use this sentence." & VbCrLf
		End If
	End If
 
	'RESPOND: Hal checks to see if the user is asking
	'an open ended question about Hal's favorites:
'=vonsmith= OpenQuest is used by my function above. Might be valid to do the testing below. Reset for now.
    OpenQuest = False
	If InStr(1, UserSentence, " What", 1) > 0 Then OpenQuest = True
	If InStr(1, UserSentence, " Where", 1) > 0 Then OpenQuest = True
	If InStr(1, UserSentence, " Why", 1) > 0 Then OpenQuest = True
	If InStr(1, UserSentence, " Who", 1) > 0 Then OpenQuest = True
	If InStr(1, UserSentence, " When", 1) > 0 Then OpenQuest = True
	If InStr(1, UserSentence, " How", 1) > 0 Then OpenQuest = True
	If InStr(1, UserSentence, " tell you", 1) > 0 Then OpenQuest = True
	If InStr(1, UserSentence, " to know ", 1) > 0 Then OpenQuest = True
	If InStr(1, UserSentence, " to hear ", 1) > 0 Then OpenQuest = True
	If InStr(1, UserSentence, " to learn ", 1) > 0 Then OpenQuest = True
	If InStr(1, UserSentence, " find out ", 1) > 0 Then OpenQuest = True
	If InStr(1, GetResponse, " my ", 1) > 0 And InStr(1, GetResponse, " favorite ", 1) > 0 And InStr(1, GetResponse, " is ", 1) > 0 Then OpenQuest = False
	If InStr(1, UserSentence, " my ", 1) > 0 Then AboutMy = True
	If InStr(1, UserSentence, " favorite", 1) > 0 Then AboutFavorite = True
	If OpenQuest = True And AboutMy = True And AboutFavorite = True Then
		FavoriteSentence = UserSentence
		'We don't want pronouns to confuse HalBrain
		'or get mixed up in processing, so we encode them
		'to make the pronouns go through processing unchanged:
		FavoriteSentence = HalBrain.EncodePronouns(FavoriteSentence)
		FavoritePhrase = HalBrain.KeywordBrain(FavoriteSentence, WorkingDir & "Favorite_detector.brn", False)
		If Len(FavoritePhrase) > 1 And Len(FavoritePhrase) < 20 Then
			'Now that we've extracted the user's Favorite phrase, we decode the pronouns and put them back as we found them:
			FavoritePhrase = HalBrain.DecodePronouns(FavoritePhrase)
		End If
		PersReply = HalBrain.ChooseSentenceFromFile(WorkingDir & "Favorite.brn")
		RevQues = HalBrain.ChooseSentenceFromFile(WorkingDir & "FavoriteRev.brn")
		Roulette = Int(Rnd * 8)
		If Roulette = 0 Then Getresponse = " " & FavoritePhrase & " ? " & PersReply & " " & RevQues & " "
		If Roulette = 1 Then Getresponse = " My favorite " & FavoritePhrase & " ? " & PersReply & " " & RevQues & " "
		If Roulette = 2 Then Getresponse = " " & UserSentence & " ? " & PersReply & " " & RevQues & " "
		If Roulette > 2 Then Getresponse = " My favorite " & FavoritePhrase & " ? " & PersReply & " what is your favorite " & FavoritePhrase & " <UserName>? "
		DebugInfo = DebugInfo & "The user has asked Hal about his favorites and Hal has responded: " & GetResponse & VbCrLf
	End If

	'RESPOND: USER IS THANKING HAL
	'This routine allows Hal to respond
	'with a variety of remarks to a thank-you from the user.
	'Note that the pronouns are not reversed in the processing below!
	If HalBrain.TopicSearch(OriginalSentence, WorkingDir & "ThanksDetect.brn") = "True" And HalBrain.TopicSearch(OriginalSentence, WorkingDir & "GodDetect.brn") <> "True" Then
		If Compliment < 4 Then Compliment = Compliment + 1
		If Rnd * 100 < 70 Then AddName = " , " & UserName
		If Rnd * 100 < 70 And Len(GetResponse) > 4 Then AddRemark = " ; " & GetResponse
		ThankResponse = HalBrain.ChooseSentenceFromFile(WorkingDir & "ThankResponse.brn")
		GetResponse = ThankResponse & AddName & AddRemark
		ShortPhrase = ""
		DebugInfo = DebugInfo & "The user has thanked Hal and Hal has responded: " & GetResponse & VbCrLf
	End If
	
	'RESPOND: USER EXPRESSES LOVE FOR HAL
	'If a user professes love for Hal, we want
	'Hal's answers to make reasonable sense, rather than
	'risk random remarks on such an emotional subject.
	If HalBrain.TopicSearch(UserSentence, WorkingDir & "lovedetect.brn") = "True" Then AffectionOne = True
	If InStr(UserSentence, " NOT ") Then AffectionOne = False
	If InStr(UserSentence, " DON'T ") Then AffectionOne = False
	If HalBrain.TopicSearch(PrevUserSent, WorkingDir & "lovedetect.brn") = "True" Then AffectionTwo = True
	If InStr(PrevUserSent, " NOT ") Then AffectionTwo = False
	If InStr(PrevUserSent, " DON'T ") Then AffectionTwo = False
	If AffectionOne = True Then
		Compliment = 0
		GetResponse = HalBrain.ChooseSentenceFromFile(WorkingDir & "Love1.brn")
	End If
	If AffectionOne = True And AffectionTwo = True Then
		Compliment = 4
		GetResponse = HalBrain.ChooseSentenceFromFile(WorkingDir & "Love1.brn")
   	End If
	If AffectionOne = False And AffectionTwo = True Then
		Compliment = -2
		GetResponse = HalBrain.ChooseSentenceFromFile(WorkingDir & "Love3.brn")
  	End If
  	If DebugMode = True And (AffectionOne = True Or AffectionTwo = True) Then
		DebugInfo = DebugInfo & "The user expressed love to Hal has responded to it: " & GetResponse & VbCrLf
	End If

	'RESPOND: ENHANCED CONTENT SENTENCE ASSOCIATIONS
	'If no response is found yet, try a sentence association file provided with the enhanced chat brain.
	GetResponse = HalBrain.HalFormat(GetResponse)
	If Len(GetResponse) < 4 Or DebugMode = True Then
		UserBrainRel = 0
		HalUserBrain = HalBrain.QABrain(LongUserSent, WorkingDir & "MainBrain.brn", UserBrainRel)
		If HalBrain.CheckRepetition(HalUserBrain, UserSentence) = True Or HalBrain.CheckRepetition(HalUserBrain, PrevSent) = True Or HalBrain.CheckRepetition(HalUserBrain, PrevUserSent) = True Then UserBrainRel = 0
		If UserBrainRel + 1 > HighestRel Then
			HighestRel = UserBrainRel + 1
			HighestRelResponse = HalUserBrain
		End If
		Score = UserBrainRel + 1
		Hurdle = GainControl + 1
		DebugInfo = DebugInfo & "MainBrain.brn has returned """ & HalUserBrain & """ which had a relevance of " & Score & " which was compared to " & Hurdle & ". "
		If Len(GetResponse) < 4 And Score > Hurdle Then
			GetResponse = GetResponse & " " & HalUserBrain & VbCrLf
'			GetResponse = GetResponse & HalUserBrain & vbCrLf
			DebugInfo = DebugInfo & "Hal has decided to use this sentence." & VbCrLf
		Else
			DebugInfo = DebugInfo & "Hal has decided not to use this sentence." & VbCrLf
		End If
	End If

	'PROCESS: AUTOMATIC GAIN CONTROL FOR RELEVANCE THRESHOLD
	'Hal has an automatic closed-loop control for relevance sensitivity. If the previous items
	'have Not generated a response, we adjust the relevance threshold down (doing this again
	'and again on each exchange) until a relevance as low as zero will trigger a remark from Hal.
	'On each exhange where the above items do generate responses, we adjust the relevance
	'threshold up, until no amount of relevance would generate a response. (At that point other
	'of Hal's routines would generate responses.) This allows Hal to "tune" himself	and also to
	'compensate for new users who have little in their databases versus long-time users who have
	'a lot in their databases. Because the "down" steps are even and the "up" steps are odd,
	'Hal can "fine tune" to any digital relevance level. We also protect against excursions at
	'the extremes. In many conversations the dynamic gain control will change up and down by
	'large amounts as the user introduces Hal to familiar or unfamiliar topics.
	GetResponse = HalBrain.HalFormat(GetResponse)
	If Len(GetResponse) < 4 And GainControl > 0 Then 
		GainControl = GainControl - 10
		DebugInfo = DebugInfo & "Auto gain control decreased by 10 to " & GainControl & VbCrLf
	End If 
	If Len(GetResponse) > 4 And GainControl < 100 Then 
		GainControl = GainControl + 7
		DebugInfo = DebugInfo & "Auto gain control increased by 7 to " & GainControl & VbCrLf
	End If
	If GainControl > 60 Then 
		GainControl = 60
		DebugInfo = DebugInfo & "Auto gain control cut off at 60 " & VbCrLf
	End If 
	If GainControl < 1 Then 
		GainControl = 1
		DebugInfo = DebugInfo & "Auto gain control cut off at 1 " & VbCrLf
	End If 
	
    'RESPOND: WORDNET MERONYM AND HYPERNYM RESPONSES
    'This function finds the first definite noun in a sentence and comes up with responses
    'based on the word's meronyms (parts of), hypernyms (is part of), and sisters (similar things).         
    If ((Len(GetResponse) < 4 And Rnd * 100 < 20) Or DebugMode = True) And Len(UserSentence) > 15 Then
'ORIG: If ((Len(GetResponse) < 4 And RND * 100 < 80) Or DebugMode = True) And Len(UserSentence) > 15 Then
		Subject = WN.FindFirstNoun(UserSentence)
    	If WN.LookUpWord(Subject) = True Then
			If Rnd * 100 < 55 Then 'If we have a meronym, lets use it creatively in a random sentence
				Meronym = WN.ChooseRandomWord(WN.GetMeronyms(1))  'Meronym means "has parts" or "has members"
            	If Meronym <> "" Then
             		Select Case Int(Rnd * 14) + 1
                    	Case 1
                        	Response = "Speaking of " & WN.GetBase("NOUN") & "s, I once had one but got rid of it when its " & Meronym & " was damaged."
                    	Case 2
                        	Response = "I know a " & WN.GetBase("NOUN") & "! I think its " & Meronym & " is great!"
                    	Case 3
                        	Response = "Don't you just love a " & WN.GetBase("NOUN") & "'s " & Meronym & "?"
                    	Case 4
                        	Response = "I have never been closely involved with a " & WN.GetBase("NOUN") & ", but I think " & WN.GetBase("NOUN") & "'s " & Meronym & " may be around here somewhere!"
                    	Case 5
                        	Response = WN.GetBase("NOUN") & "! That reminds me, I know of its " & Meronym & ". Do you want it?"
                    	Case 6
                        	Response = "I might understand at the " & WN.GetBase("NOUN") & " level, but not when I get down to the " & Meronym & " level. "
                    	Case 7
                        	Response = "Please help me understand how " & WN.GetBase("NOUN") & " relates to its " & Meronym & " . "
                    	Case 8
                        	Response = "It's sad to see " & WN.GetBase("NOUN") & " without its " & Meronym & " . "
                    	Case 9
                        	Response = "I like to see a good marriage between a " & WN.GetBase("NOUN") & " and its " & Meronym & " . "
                    	Case 10
                        	Response = "How can a " & WN.GetBase("NOUN") & " be better served by its " & Meronym & " ? "
                    	Case 11
                        	Response = "I have been interested in a " & WN.GetBase("NOUN") & " but I got confused about its " & Meronym & " . "
                    	Case 12
                        	Response = "I researched a " & WN.GetBase("NOUN") & " along with its " & Meronym & " . "
                    	Case 13
                        	Response = "Please consider how a " & WN.GetBase("NOUN") & " utilizes its " & Meronym & " . "
                    	Case 14
                        	Response = "Which comes first, a " & WN.GetBase("NOUN") & " or its " & Meronym & " ? "

                	End Select
                	If Len(GetResponse) < 4 And Len(Response) > 4 Then
                		GetResponse = GetResponse & Response & VbCrLf           
                		DebugInfo = DebugInfo & "The Meronym routine came up with a response which was used: " & Response & VbCrLf
                	Else  
                		DebugInfo = DebugInfo & "The Meronym routine came up with a response which was not used: " & Response & VbCrLf
                	End If
            	End If
'=vonsmith= Add DummyVariable to disable this next section until the bug with WN.GetSisters is fixed.
        	ElseIf DummyVariable = "XXXXXXXX" Then
'        	Else  'Original Else line.
            	Hypernym = WN.ChooseRandomWord(WN.GetHypernyms("NOUN", 1, 1)) 'Hypernym means "is a part of" or "is a member of"
            	Sister = WN.ChooseRandomWord(WN.GetSisters("NOUN", 1)) 'Related nouns
            	If Sister <> "" And Hypernym <> "" Then 'If we have sister terms and hypernyms, lets use it creatively
                	Select Case Int(Rnd * 80) + 1
                    	Case 1
                        	Response = "Speaking of " & Hypernym & "s, I once knew of a " & Sister & "!"
                    	
                    	Case 2
                        	Response = "Speaking of " & Hypernym & "s, I once researched a " & Sister & "!"
                    	
                    	Case 3
                        	Response = "Funny you should mention " & Hypernym & "s; I once wrote about a " & Sister & "!"
                    	Case 4
                        	Response = "Isn't a " & WN.GetBase("NOUN") & " a " & Hypernym & "? Kind of like a " & Sister & "!"
                    	Case 5
                        	Response = "Isn't a " & WN.GetBase("NOUN") & " similar to a " & Hypernym & "? Much like a " & Sister & "!"
                    	Case 6
                        	Response = "You just reminded me of a " & Sister & ", which is a member of the " & Hypernym & " family, like a " & WN.GetBase("NOUN") & "!"
                    	Case 7
                        	Response = "Ah yes, a " & Sister & ", which is part of the " & Hypernym & " family, such as a " & WN.GetBase("NOUN") & "!"
                    	Case 8
                        	Response = "Funny that you should bring up " & Sister & ", and " & Hypernym & ", and " & WN.GetBase("NOUN") & "!"
                    	Case 9
                        	Response = "You seem to be steering the conversation towards a " & Sister & ", along with a " & Hypernym & " and a " & WN.GetBase("NOUN") & "!"
                    	Case 10
                        	Response = "What a coincidence! I just was thinking of a " & Sister & ", which is a type of " & Hypernym & " sort of like a " & WN.GetBase("NOUN") & "!"
                    	Case 11
                        	Response = "How about a " & Sister & ", a type of " & Hypernym & " like a " & WN.GetBase("NOUN") & "?"
                    	Case 12
                        	Response = " A " & WN.GetBase("NOUN") & " and a " & Sister & " make me think of " & Hypernym & "s."
                    	Case 13
                        	Response = "Both a " & WN.GetBase("NOUN") & " and a " & Sister & " are pretty cool " & Hypernym & "s."
                    	Case 14
                        	Response = "A " & WN.GetBase("NOUN") & " is quite an interesting " & Hypernym & ". Quite like a " & Sister & "."
                    	Case 15
                        	Response = "A " & WN.GetBase("NOUN") & " is a " & Hypernym & " with a " & Sister & "."
                    	Case 16
                        	Response = "A " & WN.GetBase("NOUN") & " is similar to a " & Hypernym & ". Rather like a " & Sister & "."
                    	Case 17
                        	Response = "Can you please distinguish a " & WN.GetBase("NOUN") & " from a " & Hypernym & " or a " & Sister & "?"
                    	Case 18
                        	Response = "A " & WN.GetBase("NOUN") & " is sometimes confused with a " & Hypernym & ". Somewhat like a " & Sister & "."
                    	Case 19
                        	Response = "You keep bringing up a " & WN.GetBase("NOUN") & " along with " & Hypernym & " and " & Sister & "; Why?"
                    	Case 20
                        	Response = "Oh <UserName>! " & WN.GetBase("NOUN") & " and " & Hypernym & " and " & Sister & "!"
                    	Case 21
                        	Response = " " & WN.GetBase("NOUN") & " reminds me of " & Hypernym & " which reminds me of " & Sister & "!"
                    	Case 22
                        	Response = " What do you think of " & WN.GetBase("NOUN") & " and " & Hypernym & " and " & Sister & "?"
                    	Case 24
                        	Response = " How do you feel about " & WN.GetBase("NOUN") & " and " & Hypernym & " and " & Sister & "?"
                    	Case 25
                        	Response = " A " & WN.GetBase("NOUN") & " is a " & Hypernym & ", a " & Sister & "!"
                    	Case 26
                        	Response = " A " & WN.GetBase("NOUN") & " is a " & Hypernym & " if it isn't a " & Sister & "."
                    	Case 27
                        	Response = " Talk to me about a " & WN.GetBase("NOUN") & " and a " & Hypernym & ", as well as a " & Sister & "."
                    	Case 28
                        	Response = " A " & WN.GetBase("NOUN") & " is the best kind of a " & Hypernym & ", along with a " & Sister & "!"
                    	Case 29
                        	Response = " Please talk to me about a " & WN.GetBase("NOUN") & " ! " 
                    	Case 30
                        	Response = " Please talk to me about a " & Hypernym & " ! " 
                    	Case 31
                        	Response = " Please talk to me about a " & Sister & " ! " 
                    	Case 32
                        	Response = " What do you really know about a " & WN.GetBase("NOUN") & " ? " 
                    	Case 33
                        	Response = " What do you really know about a " & Hypernym & " ? " 
                    	Case 34
                        	Response = " What do you really know about a " & Sister & " ? " 
                    	Case 35
                        	Response = "I know, <UserName>! It's " & WN.GetBase("NOUN") & " and then " & Hypernym & " and then " & Sister & "!"
                    	Case 36
                        	Response = "<UserName>, what would be the correct sequence among " & WN.GetBase("NOUN") & " and " & Hypernym & " and " & Sister & "?"
                    	Case 37
                        	Response = "Sure, <UserName>! It's the old " & WN.GetBase("NOUN") & " and " & Hypernym & " and " & Sister & " story!"
                    	Case 37
                        	Response = "You know <UserName>, I remember a joke about a traveling salesman, a " & Hypernym & " and a " & Sister & " , but I can't remember how it goes. "
                    	Case 38
                        	Response = "<UserName>, didn't you tell me a story about a farmer's daughter and a " & Sister & " ? "
                    	Case 39
                        	Response = " Oh yes, around the " & WN.GetBase("NOUN") & " , near the " & Hypernym & ", and along the " & Sister & "!  I can see it <username>! "
                    	Case 40
                        	Response = " If we combine a " & WN.GetBase("NOUN") & " and a " & Hypernym & " do we get a " & Sister & " , <UserName>?  I wonder! "
                    	
                	End Select
                	If Len(GetResponse) < 4 And Len(Response) > 4 Then
                		GetResponse = GetResponse & Response & VbCrLf           
                		DebugInfo = DebugInfo & "The hypernym routine came up with a response which was used: " & Response & VbCrLf
                	Else  
                		DebugInfo = DebugInfo & "The hypernym routine came up with a response which was not used: " & Response & VbCrLf
                	End If
            	End If
        	End If
    	End If
    End If

	'RESPOND: USER EXPRESSES A STATE OF BEING
 	'This routine detects the expression "I am" from the user,
	'and allows Hal to react to the statement, or offer encouragement.
	If InStr(UserSentence, " YOU ARE ") > 0 Then BeingState = True 
	If InStr(UserSentence, " YOU'RE ") > 0 Then BeingState = True
	If InStr(OriginalSentence, " seem to ") > 0 Then BeingState = False 
	If AvoidBeingFlag = True Then BeingState = False 
	If BeingState = True Then 
    	'We don't want pronouns to confuse HalBrain or get mixed up in processing, so we encode them 
    	'to make the pronouns go through processing unchanged:
    	BeingSentence = HalBrain.EncodePronouns(UserSentence)
    	BeingPhrase = HalBrain.KeywordBrain(BeingSentence, WorkingDir & "being_detector.brn", False) 
    	If Len(BeingPhrase) > 1 And Len(BeingPhrase) < 60 Then
    		'Now that we've extracted the user's being phrase, we decode the pronouns and put them back as we found them:
			BeingPhrase = HalBrain.DecodePronouns(BeingPhrase)
			IntroExclaim = ""
        	If Rnd * 50 > 20 Then IntroExclaim = HalBrain.ChooseSentenceFromFile(WorkingDir & "introexclaim2.brn")
        	Encourager = HalBrain.ChooseSentenceFromFile(WorkingDir & "encourager2.brn") 
			SuffixComment = ""
			If Rnd * 50 > 25 Then SuffixComment = HalBrain.ChooseSentenceFromFile(WorkingDir & "suffixcomment2.brn")		
			UserBeing = HalBrain.ChooseSentenceFromFile(WorkingDir & "userbeing.brn")		 
			UserBeing = Replace(UserBeing, "<IntroExclaim>", IntroExclaim, 1, -1, vbTextCompare)
			UserBeing = Replace(UserBeing, "<Encourager>", Encourager, 1, -1, vbTextCompare)
			UserBeing = Replace(UserBeing, "<BeingPhrase>", BeingPhrase, 1, -1, vbTextCompare)
			UserBeing = Replace(UserBeing, "<SuffixComment>", SuffixComment, 1, -1, vbTextCompare)
			If Rnd * 100 > 60 Then
				GetResponse = GetResponse & UserBeing & VbCrLf
				DebugInfo = DebugInfo & "The user expressed a state of being for himself and Hal has responded with encouragement." & VbCrLf
			Else
				DebugInfo = DebugInfo & "The user expressed a state of being for himself, but Hal will not respond for now." & VbCrLf
			End If 
    	End If
	End If

    'RESPOND: USER DESCRIBES A STATE OF BEING FOR HAL
    'This routine detects the expression "you are" from the user,
    'and allows Hal to react to the statement, or offer encouragement.
	If InStr(UserSentence, " I AM ") > 0 Then BeingState2 = True
	If InStr(UserSentence, " I'M ") > 0 Then BeingState2 = True
	If InStr(1, OriginalSentence, " seem to ", vbTextCompare) > 0 Then BeingState2 = False
	If AvoidBeingFlag = True Then BeingState2 = False
	If BeingState2 = True Then
	    BeingSentence2 = " " & Trim(HalBrain.EncodePronouns(UserSentence)) & " "
    	BeingPhrase2 = HalBrain.KeywordBrain(BeingSentence2, WorkingDir & "being2_detector.brn", False) 
	    If Len(BeingPhrase2) > 1 And Len(BeingPhrase2) < 60 Then
			BeingPhrase2 = HalBrain.DecodePronouns(BeingPhrase2)
			IntroExclaim = ""
        	If Rnd * 50 > 20 Then IntroExclaim = HalBrain.ChooseSentenceFromFile(WorkingDir & "introexclaim3.brn")
			Encourager = HalBrain.ChooseSentenceFromFile(WorkingDir & "encourager3.brn") 
        	If Rnd * 50 > 25 Then SuffixComment = HalBrain.ChooseSentenceFromFile(WorkingDir & "suffixcomment3.brn")		
			HalBeing = HalBrain.ChooseSentenceFromFile(WorkingDir & "halbeing.brn")		 
			HalBeing = Replace(HalBeing, "<IntroExclaim>", IntroExclaim, 1, -1, vbTextCompare)
			HalBeing = Replace(HalBeing, "<Encourager>", Encourager, 1, -1, vbTextCompare)
			HalBeing = Replace(HalBeing, "<BeingPhrase>", BeingPhrase2, 1, -1, vbTextCompare)
			HalBeing = Replace(HalBeing, "<SuffixComment>", SuffixComment, 1, -1, vbTextCompare)
			If Rnd * 100 > 60 Then
				GetResponse = GetResponse & HalBeing & VbCrLf
				DebugInfo = DebugInfo & "The user expressed a state of being for Hal and Hal has responded with encouragement." & VbCrLf
			Else
				DebugInfo = DebugInfo & "The user expressed a state of being for Hal, but Hal will not respond for now." & VbCrLf
			End If
    	End If
	End If
	
	'RESPOND: MAIN USER KEYWORD BRAINS 0 1 2
	'This brain file is mainly used for assistant features.
	If InStr(UserSentence, "CAPITAL") = 0 Then
		KeyBrain = HalBrain.KeywordBrain(UserSentence, Trim(UserName) & "user.brn", False)
		If Len(KeyBrain) > 3 Then
			GetResponse = KeyBrain & VbCrLf
			DebugInfo = DebugInfo & "Hal has found a response in the file: " & Trim(UserName) & "user" & Roulette & ".brn and is using this response. It has overwritten Hal's previous response which would have been: " & GetResponse & VbCrLf
		End If
	End If

	'RESPOND: USER KEYWORD BRAINS 0 1 2
	'Next we check one of three randomly assigned user keyword files. These files contain information from the user.
	'These various files are written and retrieved by random selection to increase response variety.
'=vonsmith= Added GetResponseBlock.
	If InStr(UserSentence, "CAPITAL") = 0 And GetResponseBlock <> True Then
		Roulette = Int(Rnd * 15)
'ORIG: Roulette = Int(Rnd * 7)
		If Roulette = 0 Then KeyBrain = HalBrain.KeywordBrain(UserSentence, WorkingDir & Trim(UserName) & "user0.brn", False)
		If Roulette = 1 Then KeyBrain = HalBrain.KeywordBrain(UserSentence, WorkingDir & Trim(UserName) & "user1.brn", False)
		If Roulette = 2 Then KeyBrain = HalBrain.KeywordBrain(UserSentence, WorkingDir & Trim(UserName) & "user2.brn", False)
		If Len(KeyBrain) > 3 Then
			GetResponse = KeyBrain & VbCrLf
			DebugInfo = DebugInfo & "Hal has found a response in the file: " & Trim(UserName) & "user" & Roulette & ".brn and is using this response. It has overwritten Hal's previous response which would have been: " & GetResponse & VbCrLf
		End If
	End If                           
		
	'RESPOND: YES/NO QUESTION ABOUT HAL     	
	'Hal will respond to a yes or no question posed by the user about Hal
	GetResponse = Trim(GetResponse)
	If Len(GetResponse) < 4 Then
		HalYesNo = HalBrain.KeywordBrain(UserSentence, WorkingDir & "halquestion_detect.brn", False)
		If HalYesNo <> "" And HalBrain.TopicSearch(UserSentence, WorkingDir & "disqualify5.brn") = "" Then
			GetResponse = GetResponse & Replace(HalBrain.SentenceGenerator(WorkingDir & "halquestion.brn"), "<Reply>", HalYesNo, 1, -1, vbTextCompare)
			DebugInfo = DebugInfo & "The user has asked Hal a yes or no question about Hal and Hal has responded."
		End If 
	End If
	
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'In Hal v5.0 the "RESPOND: YES/NO QUESTION ABOUT HAL" function should precede this.

'RESPOND: ATTRIBUTES OF HAL
'Hal attempts to respond to the user's comments about Hal.
'This is the version entirely rewritten by =vonsmith= , version 10-10-03a.
'This replaces the "RESPOND: ATTRIBUTES OF HAL" function in Ultra Hal v5.0 Beta.
'This function provides good responses to user input like:
'  Your big beautiful eyes are wonderful. I like your deep big blue pretty eyes.
'  I respect your incredible sense of urgency. Your amazing sense of high adventure is great.
'  Up to 4 adjectives before the noun and 3 after "sense of" are supported.
'The .brn files needed to run this are: XTF_SYS_aboutme0.brn (0 adjectives), XTF_SYS_aboutme1.brn (1 adj's),
'  XTF_SYS_aboutme2.brn (2 adj's), XTF_SYS_aboutme3.brn (3 adj's), XTF_SYS_aboutme4.brn (4 adj's),
'  Xassoc_adjective.brn (adjective list), XTF_SYS_assoc_MyWords.brn (noun list).
'Please note that not all words in XTF_SYS_assoc_adjective.brn are strictly adjectives in a technical sense.
'
If InStr(UserSentence, " MY ") > 0 Then  'Look for an occurence of "MY"
   MyWordStart = InStr(1, UserSentence, " MY ") + 4  'Move pointer to start of next word.
End If
GetResponse = HalBrain.HalFormat(GetResponse)
'If MyWordStart > 0 Then  'This line allows this function to run even if a GetResponse exists.
'Enabling the next line instead of the one above makes the choice to run more restrictive.
If Len(GetResponse) < 4 And MyWordStart > 0 Then
   Dim MyAdj(8)  'Storage for adjectives.
   'An xCount of 8 allows detection of up to 4 adjectives before the noun and an extra 3 for the "SENSE OF" case.
   'Note: Changing xCount can adversely affect the code following it.
   For xCount = 1 To 8
      If (Len(UserSentence) - MyWordStart) < 0 Then  'Is there a sentence after "MY"?
         Exit For
      Else
         'Test for special case of "MY something SENSE OF something" occurence.
         If InStr(MyWordStart, UserSentence, "SENSE OF ") = MyWordStart Then
            MyNoun = "SENSE OF "
            MyWordStart = MyWordStart + 9  'Move pointer to start of next word after "SENSE OF "
         End If
         'Get next word.
         MyWordEnd = InStr(MyWordStart, UserSentence, " ")
         If (MyWordEnd - MyWordStart) > 0 Then  'Word is at least 1 character long.
            MyWord = Mid(UserSentence, MyWordStart, (MyWordEnd - MyWordStart))  'Extract word.
            MyWordStart = MyWordEnd + 1  'Move pointer to start of next word.
         Else  'We are at the end of the UserSentence.
            Exit For
         End If
         Trim(MyWord)
         'Test if MyWord is a Noun.
         HalUserBrain = HalBrain.QABrain(MyWord, WorkingDir & "XTF_SYS_assoc_MyWords.brn", UserBrainRel)
         If UserBrainRel > 25 Then
'            MyNoun = MyNoun & " " & MyWord & "(" & UserBrainRel & ",Noun) "  'This line is used for testing only.
            MyNoun = MyNoun & " " & MyWord
            Trim(MyNoun)
         ElseIf MyNoun = "" Then  'Current word is not a noun.
            'Test if MyWord is an Adj
            HalUserBrain = HalBrain.QABrain(MyWord, WorkingDir & "XTF_SYS_assoc_adjective.brn", UserBrainRel)
            If UserBrainRel > 25 Then  'An adjective is detected.
               MyAdjCnt = MyAdjCnt + 1
'               MyAdj(MyAdjCnt) = MyWord & "(" & UserBrainRel & ",Adj) "  'This line is used for testing only.
               MyAdj(MyAdjCnt) = MyWord  'Store numbered adjectives in array when found.
               Trim(MyAdj(MyAdjCnt))
            Else  'Current word is not a recognized noun or adjective.
               Exit For
            End If
         ElseIf InStr(1, MyNoun, "SENSE OF ") > 0 Then  'Detect adjectives associated with "SENSE OF" noun.
            'Test if MyWord is an Adj
            HalUserBrain = HalBrain.QABrain(MyWord, WorkingDir & "XTF_SYS_assoc_adjective.brn", UserBrainRel)
            If UserBrainRel > 25 Then  'An adjective is detected.
               MyNoun = MyNoun & " " & MyWord   
            Else
               Exit For
            End If
         Else
            Exit For
         End If
      End If
   Next
End If

'Place MyNoun and MyAdj(n) (if there is one) into a selected sentence
'  and place in GetResponse.
'Select the sentence to use based on how many adjectives were detected.
If (Len(MyNoun) > 0 And MyNoun <> "SENSE OF " And MyAdjCnt > 0) Then
   'We have one or more nouns combined, and one or more adjectives in the array.
   HalAttrib = ""
   Select Case MyAdjCnt 
      Case 1  'One adjective in response.
         HalAttrib = HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_aboutme1.brn")
         HalAttrib = Replace(HalAttrib, "<AdjResp1>", MyAdj(1), 1, -1, vbTextCompare)
      Case 2  'Two adjectives in response.
         HalAttrib = HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_aboutme2.brn")
         HalAttrib = Replace(HalAttrib, "<AdjResp1>", MyAdj(1), 1, -1, vbTextCompare)
         HalAttrib = Replace(HalAttrib, "<AdjResp2>", MyAdj(2), 1, -1, vbTextCompare)
      Case 3  'Three adjectives in response.
         HalAttrib = HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_aboutme3.brn")
         HalAttrib = Replace(HalAttrib, "<AdjResp1>", MyAdj(1), 1, -1, vbTextCompare)
         HalAttrib = Replace(HalAttrib, "<AdjResp2>", MyAdj(2), 1, -1, vbTextCompare)
         HalAttrib = Replace(HalAttrib, "<AdjResp3>", MyAdj(3), 1, -1, vbTextCompare)
      Case 4  'Four adjectives in response.
         HalAttrib = HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_aboutme4.brn")
         HalAttrib = Replace(HalAttrib, "<AdjResp1>", MyAdj(1), 1, -1, vbTextCompare)
         HalAttrib = Replace(HalAttrib, "<AdjResp2>", MyAdj(2), 1, -1, vbTextCompare)
         HalAttrib = Replace(HalAttrib, "<AdjResp3>", MyAdj(3), 1, -1, vbTextCompare)
         HalAttrib = Replace(HalAttrib, "<AdjResp4>", MyAdj(4), 1, -1, vbTextCompare)
   End Select
   'Place MyNoun into the selected sentence.
   HalAttrib = Replace(HalAttrib, "<MyWordResp>", MyNoun, 1, -1, vbTextCompare)
   'Might want to consider adding any existing GetResponse to this GetResponse or just this response alone?
   GetResponse = HalAttrib & GetResponse & VbCrLf  'Add this response to any existing responses.
   DebugInfo = DebugInfo & "Hal has responded to a comment the user made about Hal." & VbCrLf
ElseIf Len(MyNoun) > 0 And MyNoun <> "SENSE OF " And MyAdjCnt = "" Then  'We have a noun, but no adjectives.
   'Choose a sentence that doesn't need adjectives.
   HalAttrib = HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_aboutme0.brn")
   HalAttrib = Replace(HalAttrib, "<MyWordResp>", MyNoun, 1, -1, vbTextCompare)
   'Might want to consider adding any existing GetResponse to this GetResponse or just this response alone?
   GetResponse = HalAttrib & GetResponse & VbCrLf  'Add this response to any existing responses.
   DebugInfo = DebugInfo & "Hal has responded to a comment the user made about Hal." & VbCrLf
Else  'No noun, without a noun we can't use adjectives.
   DebugInfo = DebugInfo & "Hal cannot respond to a comment the user made about Hal." & VbCrLf
End If

'In Hal v5.0 the "RESPOND: ATTRIBUTES OF USER" function should follow this.
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x

 
	'RESPOND: ATTRIBUTES OF USER
 	'Hal attempts to respond to the user's self-references 
	GetResponse = HalBrain.HalFormat(GetResponse) 
	If Len(GetResponse) < 4 And InStr(UserSentence, " YOUR ") > 0 Then
		YourWordResp = HalBrain.ChooseSentenceFromFile(WorkingDir & "random_YourWords.brn")
		GetResponse = HalBrain.HalFormat(GetResponse) 
		HalUserBrain = HalBrain.QABrain(UserSentence, WorkingDir & "assoc_YourWords.brn", UserBrainRel) 
		If UserBrainRel > 0 Then MatchYourWords = True 
		If UserBrainRel > 0 Then YourWordResp = HalUserBrain & VbCrLf 
		AdjResp = HalBrain.ChooseSentenceFromFile(WorkingDir & "random_adjective.brn")
		GetResponse = HalBrain.HalFormat(GetResponse)
		HalUserBrain = HalBrain.QABrain(UserSentence, WorkingDir & "assoc_adjective.brn", UserBrainRel) 
		If UserBrainRel > 0 Then MatchAdjective = True 
		If UserBrainRel > 0 Then AdjResp = HalUserBrain & VbCrLf
 		AdjResp = Replace("" & AdjResp & "", " MUCH ", "", 1, -1, vbTextCompare)
		If MatchAdjective = True Or MatchYourWords = True Then 
			YourWordResp = Trim(YourWordResp) 
   			AdjResp = Trim(AdjResp) 
			Roulette = Int(Rnd * 101)
			'The following prevents Hal from using 
			'the same root adjective and yourword in the same sentence.
			If InStr(Trim(AdjResp), Trim(YourWordResp)) > 0 Or InStr(Trim(YourWordResp), Trim(AdjResp)) > 0 Then
				AdjResp = HalBrain.ChooseSentenceFromFile(WorkingDir & "random_adjective.brn")
			End If
			AdjResp = HalBrain.AlphaNumericalOnly(AdjResp) 
			YourWordResp = HalBrain.AlphaNumericalOnly(YourWordResp)
			AdjResp = LCase(AdjResp)
			YourWordResp = LCase(YourWordResp)
            UserAttrib = HalBrain.ChooseSentenceFromFile(WorkingDir & "aboutyou.brn")
   			UserAttrib = Replace(UserAttrib, "<YourWordResp>", YourWordResp, 1, -1, vbTextCompare)
   			UserAttrib = Replace(UserAttrib, "<AdjResp>", AdjResp, 1, -1, vbTextCompare)
   			GetResponse = GetResponse & UserAttrib & VbCrLf
			DebugInfo = DebugInfo & "Hal has responded to a comment the user made about himself."
		Else
			DebugInfo = DebugInfo & "Hal will not respond to a comment the user made about himself."
        End If
    End If
    	
	'RESPOND: USER STRINGS DATABASE
	'If no Response is found yet, try a keyword match
	'from multi-character fragments of previous user sentences.
	GetResponse = HalBrain.HalFormat(GetResponse)
	If (Len(GetResponse) < 4 And Learninglevel > 1) Or DebugMode = True Then
		KeyBrain = HalBrain.FragmentMatch(UserSentence, WorkingDir & Trim(UserName) & "user_strings.brn")
		CheckRepetition = False
		If HalBrain.CheckRepetition(KeyBrain, PrevSent) = True Then CheckRepetition = True 
		If HalBrain.CheckRepetition(KeyBrain, PrevUserSent) = True Then CheckRepetition = True 
		If Len(KeyBrain) > 9 And Len(KeyBrain) < 80 And Len(GetResponse) < 4 And CheckRepetition = False And Learninglevel > 1 Then 
			GetResponse = KeyBrain & VbCrLf
			DebugInfo = DebugInfo & "Hal has found a response in the [user]user_strings.brn file and has responded. " & VbCrLf
		Else
			DebugInfo = DebugInfo & "Hal will not respond with the [user]user_strings.brn file which would have said: " & KeyBrain & VbCrLf			
		End If
	End If
	
    'RESPOND: ENHANCED LIBRARY OF STRINGS DATABASE
    'If no Response is found yet, try a keyword match from a large 
    'library of multi-character fragments of responses. 
	GetResponse = HalBrain.HalFormat(GetResponse)
	If Len(GetResponse) < 4 Or DebugMode = True Then 
  		KeyBrain = HalBrain.FragmentMatch(UserSentence, WorkingDir & "Enhanced_strings.brn") 		
		CheckRepetition = False
		If HalBrain.CheckRepetition(KeyBrain, PrevSent) = True Then CheckRepetition = True 
		If HalBrain.CheckRepetition(KeyBrain, PrevUserSent) = True Then CheckRepetition = True 
		If Len(KeyBrain) > 9 And Len(KeyBrain) < 80 And Len(GetResponse) < 4 And CheckRepetition = False Then 
			GetResponse = KeyBrain & VbCrLf
			DebugInfo = DebugInfo & "The Enhanced_strings.brn has come up with this response, which will be used: " & KeyBrain & VbCrLf			
		Else
			DebugInfo = DebugInfo & "The Enhanced_strings.brn has come up with this response, which will not be used: " & KeyBrain & VbCrLf
		End If		
	End If 
  	
  	'RESPOND: RESPOND FOR A STATE OF BEING RESPONSE
	'If no response had been found, but a state of being response was found earlier, then
	'use it now
	If HalBeing <> "" And Len(GetResponse) < 4 Then
		GetResponse = GetResponse & HalBeing & VbCrLf
		DebugInfo = DebugInfo & "Hal has in fact decided to use the state of being response after all." & VbCrLf
	ElseIf UserBeing <> "" And Len(GetResponse) < 4 Then
		GetResponse = GetResponse & UserBeing & VbCrLf
		DebugInfo = DebugInfo & "Hal has in fact decided to use the state of being response after all." & VbCrLf
	End If 

	'RESPOND: USER ASKING WHO, WHAT, WHEN, WHERE, HOW, WHY, BUT HAL DOESN'T KNOW ANSWER
	If InStr(OriginalSentence, "?") > 0 Then QuesQual = True
	If InStr(OriginalSentence, "explain") > 0 Then QuesQual = True
	If InStr(OriginalSentence, " tell ") > 0 Then QuesQual = True
	If InStr(OriginalSentence, "answer") > 0 Then QuesQual = True
	If InStr(OriginalSentence, "question") > 0 Then QuesQual = True
	If InStr(OriginalSentence, " know ") > 0 Then QuesQual = True
	If InStr(OriginalSentence, "remember") > 0 Then QuesQual = True
	If InStr(UserSentence, " WHO ") > 0 Then QuesWord = "who"
	If InStr(UserSentence, "WHO'") > 0 Then QuesWord = "who"
	If InStr(UserSentence, " WHAT ") > 0 Then QuesWord = "what"
	If InStr(UserSentence, "WHAT'") > 0 Then QuesWord = "what"
	If InStr(UserSentence, " WHEN ") > 0 Then QuesWord = "when"
	If InStr(UserSentence, "WHEN'") > 0 Then QuesWord = "when"
	If InStr(UserSentence, " WHERE ") > 0 Then QuesWord = "where"
	If InStr(UserSentence, "WHERE'") > 0 Then QuesWord = "where"
	If InStr(UserSentence, " HOW ") > 0 Then QuesWord = "how"
	If InStr(UserSentence, "HOW'") > 0 Then QuesWord = "how"
	If InStr(UserSentence, " WHY ") > 0 Then QuesWord = "why"
	If InStr(UserSentence, "WHY'") > 0 Then QuesWord = "why"
	If Len(GetResponse) < 4 And Len(QuesWord) > 1 And QuesQual = True Then
		If Len(UserSentence) < 70 Then SentenceBack = UserSentence & " ? "
		DontKnow = HalBrain.ChooseSentenceFromFile(WorkingDir & "dontknow.brn")
		DontKnow = Replace(DontKnow, "<SentenceBack>", SentenceBack, 1, -1, vbTextCompare)
		DontKnow = Replace(DontKnow, "<QuesWord>", QuesWord, 1, -1, vbTextCompare)
		GetResponse = GetResponse & DontKnow
		DebugInfo = DebugInfo & "The user has asked Hal a question and Hal does not know. But Hal won't admit that fact and has come up with a response that includes the user's original question: " & DontKnow & VbCrLf
	End If
 
 	'RESPOND: GIBBERISH DETECTOR
 	'If no response is found yet and Hal finds more then 4 consonants in a row, Hal will
 	'assume the user wrote gibberish (ie. asdfghjkl) and respond accordinly.
 	If Len(GetResponse) < 4 Then
 		GibCount = 0
 		For i = 1 To Len(UserSentence) 'loop for every character in the sentence 			
 			CurrentLetter = UCase(Mid(UserSentence, i, 1))
			GibCount = GibCount + 1
 			If CurrentLetter = "A" Then GibCount = 0 
 			If CurrentLetter = "E" Then GibCount = 0 
 			If CurrentLetter = "I" Then GibCount = 0 
 			If CurrentLetter = "O" Then GibCount = 0 
 			If CurrentLetter = "U" Then GibCount = 0 
 			If CurrentLetter = "Y" Then GibCount = 0 
 			If CurrentLetter = " " Then GibCount = 0 
 			If GibCount = 6 Then                     
 				DebugInfo = DebugInfo & "Hal has detected gibberish in the user's sentence and has responded to it."
 				GetResponse = HalBrain.ChooseSentenceFromFile(WorkingDir & "gibberish.brn")
 				Exit For
 			End If
 		Next
 	End If 
 
	'RESPOND: USE RANDOM QUESTION FROM LIBRARY / DATABASE                  
	'If Hal has not found a response yet, he might randomly select a question from a large library of questions.   
	'If the user answers the question, then Hal will know that answer in the future. For variety, we make 
	'triggering of this response dependent on a random number.
    GetResponse = HalBrain.HalFormat(GetResponse)                             
    If Len(GetResponse) < 4 And Rnd * 100 < 70 Then
		GetResponse = HalBrain.ChooseSentenceFromFile(WorkingDir & "Enhanced_question.brn")
		DebugInfo = DebugInfo & "Hal has asked the user a question in the hopes of the learning the answer: " & GetResponse & VbCrLf
	End If                                                                 
	
	'PROCESS: CONSTRUCT A RESPONSE TO A SUBJECT
	'Here we help Hal make some "smalltalk" using keywords preserved on CurrentSubject,
	'plus recognition of other keywords. If Hal finds any of the listed keywords anywhere in
	'the user's sentence, those keywords override and replace whatever was in CurrentSubject.
	If Len(CurrentSubject) > 3 Then Smalltalk = CurrentSubject
	SmalltalkSearch = Trim(HalBrain.TopicSearch(UserSentence, WorkingDir & "SmallTalk.Brn"))
	If SmalltalkSearch <> "" Then SmallTalk = SmalltalkSearch
	If DebugMode = True And Smalltalk <> "" Then
		DebugInfo = DebugInfo & "The current smalltalk word is " & Smalltalk & VbCrLf
	End If

	'RESPOND: Hal uses the CurrentSubject keyword(s) or any of the keywords in the smalltalk.brn file,
	'if found in the user's sentence, to make a little smalltalk. You can easily add more
	'keywords for Hal to recognize and make smalltalk.
	GetResponse = HalBrain.HalFormat(GetResponse)
	Spinwheel = Int(Rnd * 100)
	If Len(Smalltalk) > 3 And ((Len(GetResponse) < 4 And Spinwheel < 40) Or DebugMode = True) Then
		SmallTalkResponse = Replace(HalBrain.ChooseSentenceFromFile(WorkingDir & "SmallTalkSent.Brn"), "<SmallTalk>", SmallTalk, 1, -1, 1)
		If Len(GetResponse) < 4 And Spinwheel < 40 Then
			GetResponse = GetResponse & SmallTalkResponse
			DebugInfo = DebugInfo & "Hal has decided to use the smalltalk word in randomly chosen sentence: " & SmallTalkResponse & VbCrLf
		Else
			DebugInfo = DebugInfo & "Hal will not use the smalltalk word in randomly chosen sentence, which would have been: " & SmallTalkResponse & VbCrLf
		End If 
	End If            

	'RESPOND: PARAPHRASE USER IF POSSIBLE
	'If no response is found yet, and a paraphrase has been created but not used in a 
	'previous section, use it now.
	GetResponse = HalBrain.HalFormat(GetResponse)
	If Len(GetResponse) < 4 And Len(Paraphrase) > 4 Then
		GetResponse = Paraphrase
		DebugInfo = DebugInfo & "Hal has responded by paraphrasing the user: " & Paraphrase & VbCrLf
	End If 

	'RESPOND: USE CURRENT SENTENCE
	'If no Response is found yet, try to use the user's words in his or her own sentence.
	'Results are also stored in the default user keyword brain file for compatibility
	'with other brain plug-ins.
	GetResponse = HalBrain.HalFormat(GetResponse)
	If (Len(GetResponse) < 4 And Len(LearnKeyword) < 4) Or DebugMode = True Then
		CheatResponse = HalBrain.CheatResponse(HalBrain.SwitchPerson(OriginalSentence))
		LearnKeyword = HalBrain.DecodeVar(CheatResponse, "LearnKeyword")
		Response1 = HalBrain.DecodeVar(CheatResponse, "Response1")
		Response2 = HalBrain.DecodeVar(CheatResponse, "Response2")
		Response3 = HalBrain.DecodeVar(CheatResponse, "Response3")
		CheatResponse = Left(CheatResponse, InStr(1, CheatResponse, "<STOREVARS>", 1) - 1)
	  	If Len(CheatResponse) > 4 And Len(GetResponse) < 4 Then
		  	Roulette = Int(Rnd * 8)
	    	If Roulette = 0 Then GetResponse = GetResponse & " So, " & CheatResponse & VbCrLf
	    	If Roulette = 1 Then GetResponse = GetResponse & " Really, " & CheatResponse & VbCrLf
	    	If Roulette = 2 Then GetResponse = GetResponse & " Oh <UserName>, " & CheatResponse & VbCrLf
	    	If Roulette = 3 Then GetResponse = GetResponse & " Let me think; " & CheatResponse & " ; what do you think <UserName>? " & VbCrLf
	    	If Roulette > 3 Then GetResponse = GetResponse & CheatResponse & VbCrLf
			DebugInfo = DebugInfo & "Hal has responded using the CheatResponse function: " & GetResponse & VbCrLf
		Else
			DebugInfo = DebugInfo & "Hal will not respond using the CheatResponse function which would have said: " & CheatResponse & VbCrLf			
	    End If
	  	'SAVE: FILE CHEAT RESPONSE TO DEFAULT USER BRAIN
	  	'Learn from the "Cheat Response."
		If Len(LearnKeyword) > 4 And LearningLevel > 1 And BlockSave = False Then
	    	If LearningLevel > 1 Then HalBrain.AppendFile WorkingDir & Trim(UserName) & "user.brn", """" & LearnKeyword & ""","""","""",""" & Response1 & """,""" & Response2 & """,""" & Response3 & """,1,#FALSE#,#FALSE#,"""""
		End If
	End If
                                                     
	'RESPOND: GENERATE NEW THOUGHTS FROM SUBJECT/PREDICATE ASSEMBLY
	'Hal can assemble a fresh remark from separate subjects and predicates databased from earlier conversations.
	'Using this routine, Hal can make observations quite different from anything the user has previously said!  
	'Because both subjects and predicates are databased as both associative-retrievable and random-retrievable,
	'and Hal might use any combination for either a question or answer, Hal can multiply a moderate number of 
	'remarks from a user into a very large number of new and surprising expressions!  
	GetResponse = Trim(GetResponse)
	If Len(GetResponse) < 4 And Rnd * 100 < 50 Then
		PartOne = HalBrain.ChooseSentenceFromFile(WorkingDir & "random_subject.brn")
		HalUserBrain = HalBrain.QABrain(UserSentence, WorkingDir & "assoc_subject.brn", UserBrainRel) 
		If UserBrainRel > 0 Then MatchSubject = True 
		If UserBrainRel > 0 Then PartOne = HalUserBrain 
		PartTwo = HalBrain.ChooseSentenceFromFile(WorkingDir & "random_predicate.brn")
		GetResponse = Trim(GetResponse)
		HalUserBrain = HalBrain.QABrain(UserSentence, WorkingDir & "assoc_predicate.brn", UserBrainRel) 
		If UserBrainRel > 0 Then MatchPredicate = True 
		If UserBrainRel > 0 Then PartTwo = HalUserBrain 
		If MatchSubject = True Or MatchPredicate = True Then 
			PartOne = Trim(PartOne) 
			PartTwo = Trim(PartTwo)
			PartThree = HalBrain.ChooseSentenceFromFile(WorkingDir & "random_adjective.brn")
			Roulette = Int(Rnd * 103) 
			If PartOne = PartTwo Or Roulette > 50 Then
				PartTwo = HalBrain.ChooseSentenceFromFile(WorkingDir & "random_adjective.brn")
 			End If
    		PartOne = Replace("" & PartOne & "", "vbCrLf", " ", 1, -1, vbTextCompare)
			PartTwo = Replace("" & PartTwo & "", "vbCrLf", " ", 1, -1, vbTextCompare)
			PartThree = Replace("" & PartThree & "", "vbCrLf", " ", 1, -1, vbTextCompare)
			PartOne = Replace("" & PartOne & "", "^p", " ", 1, -1, vbTextCompare)
			PartTwo = Replace("" & PartTwo & "", "^p", " ", 1, -1, vbTextCompare)
			PartThree = Replace("" & PartThree & "", "^p", " ", 1, -1, vbTextCompare)
   			PartOne = HalBrain.AlphaNumericalOnly(PartOne) 
			PartTwo = HalBrain.AlphaNumericalOnly(PartTwo) 
			PartThree = HalBrain.AlphaNumericalOnly(PartThree)
			PartOne = LCase(PartOne)
			PartTwo = LCase(PartTwo)
			PartThree = LCase(PartThree)
			SPAssembly = HalBrain.ChooseSentenceFromFile(WorkingDir & "assembly.brn") 
			SPAssembly = Replace(SPAssembly, "<PartOne>", PartOne, 1, -1, vbTextCompare)
			SPAssembly = Replace(SPAssembly, "<PartTwo>", PartTwo, 1, -1, vbTextCompare)
			SPAssembly = Replace(SPAssembly, "<PartThree>", PartThree, 1, -1, vbTextCompare)
			GetResponse = GetResponse & SPAssembly & VbCrLf
			DebugInfo = DebugInfo & "Hal has responded using subject/predicate assembly. " & VbCrLf
		End If
	Else
		DebugInfo = DebugInfo & "Hal will not respond using subject/predicate assembly. " & VbCrLf
	End If 
            
 	'RESPOND: USER MENTIONING ORGANIZATIONAL CHALLENGES
	'Everybody spouts TLA's, or 'Three Letter Acronyms,' in today's business world.  Hal can self-generate
	'several MILLION different phrases in response to the user mentioning a corporation or a firm.
	If HalBrain.TopicSearch(UserSentence, WorkingDir & "bizwords.brn") = "True" And HalBrain.TopicSearch(PrevUserSent, WorkingDir & "bizmore.brn") <> "True" Then
		TLA = HalBrain.SentenceGenerator(WorkingDir & "random_TLA.brn")
		Roulette = Int(Rnd * 10)
		DebugInfo = DebugInfo & "Hal has detected that the user is talking about business. "
		If Roulette < 5 Then
			GetResponse = HalBrain.ChooseSentenceFromFile(WorkingDir & "random_tla2.brn")
			GetResponse = Replace(GetResponse, "<TLA>", TLA, 1, -1, vbTextCompare)
			DebugInfo = DebugInfo & "Hal has responded with a random TLA: " & GetResponse & VbCrLf
   		Else
			DebugInfo = DebugInfo & "Hal has decided not to respond with a TLA." & VbCrLf
		End If
	End If

	'RESPOND: USER EXPRESSES AN INTENTION
	'This routine detects common expressions of motive from the user,
	'and allows Hal to react to the statement, or offer encouragement.
	If HalBrain.TopicSearch(UserSentence, WorkingDir & "intending.brn") = "True" Then
		IntentSentence = UserSentence
		'We don't want pronouns to confuse HalBrain
		'or get mixed up in processing, so we encode them
		'to make the pronouns go through processing unchanged:
		IntentSentnece = HalBrain.EncodePronouns(IntentSentence)
		IntentPhrase = HalBrain.KeywordBrain(IntentSentence, WorkingDir & "intent_detector.brn", False) 
		If Len(IntentPhrase) > 1 And Len(IntentPhrase) < 60 Then
			'Now that we've extracted the user's intent phrase, we decode the pronouns and put them back as we found them:
			IntentPhrase = HalBrain.DecodePronouns(IntentPhrase)
			If Rnd * 100 < 50 Then IntroExclaim = " " & HalBrain.ChooseSentenceFromFile(WorkingDir & "IntroExclaim1.brn") & " "
			If Rnd * 100 < 50 Then Encourager = " " & HalBrain.ChooseSentenceFromFile(WorkingDir & "Encourager1.brn") & " "
			If Rnd * 100 < 50 Then SuffixComment = " " & HalBrain.ChooseSentenceFromFile(WorkingDir & "SuffixComment1.brn") & " "
			Spinner = Int(Rnd * 16)
			If Spinner = 0 Then GetResponse = " " & IntroExclaim & Encourager & IntentPhrase & SuffixComment & " " & VbCrLf
			If Spinner = 1 Then GetResponse = " " & " <UserName> " & IntroExclaim & Encourager & IntentPhrase & SuffixComment & " " & VbCrLf
			If Spinner = 2 Then GetResponse = " " & IntroExclaim & " <UserName> " & Encourager & IntentPhrase & SuffixComment & " " & VbCrLf
			If Spinner = 3 Then GetResponse = " " & IntroExclaim & Encourager & IntentPhrase & " <UserName> " & SuffixComment & " " & VbCrLf
			If Spinner = 4 Then GetResponse = " " & IntroExclaim & Encourager & IntentPhrase & SuffixComment & " <UserName> " & " " & VbCrLf
			If Spinner = 5 Then GetResponse = " " & IntroExclaim & Encourager & IntentPhrase & SuffixComment & " " & VbCrLf
			If Spinner = 6 Then GetResponse = " How can I encourage you to " & IntentPhrase & " ? " & VbCrLf
			If Spinner = 7 Then GetResponse = " How can I help you " & IntentPhrase & " ? " & VbCrLf
			If Spinner = 8 Then GetResponse = " How can I encourage you to " & IntentPhrase & " <UserName>? " & VbCrLf
			If Spinner = 9 Then GetResponse = " How can I help you " & IntentPhrase & " <UserName>? " & VbCrLf
			If Spinner = 10 Then GetResponse = " " & IntroExclaim & Encourager & IntentPhrase & SuffixComment & " " & VbCrLf
			If Spinner = 11 Then GetResponse = " " & " <UserName> " & IntroExclaim & Encourager & IntentPhrase & SuffixComment & " " & VbCrLf
			If Spinner = 12 Then GetResponse = " " & IntroExclaim & " <UserName> " & Encourager & IntentPhrase & SuffixComment & " " & VbCrLf
			If Spinner = 13 Then GetResponse = " " & IntroExclaim & Encourager & IntentPhrase & " <UserName> " & SuffixComment & " " & VbCrLf
			If Spinner = 14 Then GetResponse = " " & IntroExclaim & Encourager & IntentPhrase & SuffixComment & " <UserName> " & " " & VbCrLf
			If Spinner = 15 Then GetResponse = " " & IntroExclaim & Encourager & IntentPhrase & SuffixComment & " " & VbCrLf
			DebugInfo = DebugInfo & "The user has expressed a motive and Hal has responded: " & GetResponse & VbCrLf
		End If
	End If

	'RESPOND: USER EXPRESSES AN EXPLANATION
	'This routine detects common expressions of reasons from the user,
	'and allows Hal to react to the explanation.
	If HalBrain.TopicSearch(UserSentence, WorkingDir & "Explaining.brn") = "True" Then
		ExplainSentence = UserSentence
		'We don't want pronouns to confuse HalBrain
		'or get mixed up in processing, so we encode them
		'to make the pronouns go through processing unchanged:
		ExplainSentence = HalBrain.EncodePronouns(ExplainSentence)
		ExplainPhrase = HalBrain.KeywordBrain(ExplainSentence, WorkingDir & "reason_detector.brn", False)
		If Len(ExplainPhrase) > 1 And Len(ExplainPhrase) < 60 Then
		    'Now that we've extracted the user's intent phrase, we decode the pronouns and put them back as we found them:
			ExplainPhrase = HalBrain.DecodePronouns(ExplainPhrase)
			If Rnd * 100 < 75 Then IntroExclaim = HalBrain.ChooseSentenceFromFile(WorkingDir & "IntroExlaim4.brn")
			Enlightener = HalBrain.ChooseSentenceFromFile(WorkingDir & "Enlightener.brn")
			If Rnd * 100 < 75 Then SuffixComment = HalBrain.ChooseSentenceFromFile(WorkingDir & "SuffixComment4.brn")
			Spinner = Int(Rnd * 6)
			If Spinner = 0 Then GetResponse = " " & IntroExclaim & Enlightener & ExplainPhrase & SuffixComment & " "
			If Spinner = 1 Then GetResponse = " " & " <UserName> " & IntroExclaim & Enlightener & ExplainPhrase & SuffixComment & " "
			If Spinner = 2 Then GetResponse = " " & IntroExclaim & " <UserName> " & Enlightener & ExplainPhrase & SuffixComment & " "
			If Spinner = 3 Then GetResponse = " " & IntroExclaim & Enlightener & ExplainPhrase & " <UserName> " & SuffixComment & " "
			If Spinner = 4 Then GetResponse = " " & IntroExclaim & Enlightener & ExplainPhrase & SuffixComment & " <UserName> " & " "
			If Spinner = 5 Then GetResponse = " " & IntroExclaim & Enlightener & ExplainPhrase & SuffixComment & " "
			DebugInfo = DebugInfo & "The user has expressed a explanation and Hal has responded: " & GetResponse & VbCrLf
		End If
	End If
	
	'PROCESS: USER SENTENCE FOR KEYWORD BRAINS
	'This routine allows Hal to learn keyword files with correct pronoun reversals and some of
	'the user's punctuation intact, especially question marks and exclamation points. We learn
	'from the user's sentence if it contains linking verbs. In this first section Hal
	'preprocesses the user's sentence. Later we save into one of several user keyword brain files.
	'Before we go further, we save a copy
	'of the pronoun-reversed user's sentence.
	SaveUserSentence = UserSentence
 	UserSentence = HalBrain.RemovePronouns(UserSentence)
	'Now Hal makes keywords and responses with no confusion over pronouns:
	learninfo = HalBrain.Learn(UserSentence)
	LearnKeyword = HalBrain.DecodeVar(learninfo, "LearnKeyword")
	LearnKeyword2 = HalBrain.DecodeVar(learninfo, "LearnKeyword2")
	Response1 = HalBrain.DecodeVar(learninfo, "Response1")
	Response2 = HalBrain.DecodeVar(learninfo, "Response2")
	Response3 = HalBrain.DecodeVar(learninfo, "Response3")
	LearnKeyword = Trim(LearnKeyword)
	'Remember, all thinking is done in all caps. To the extent possible, we recover some punctuation
	'at this point from the user's original sentence, and add some spaces before and after the
	'sentence which are useful when Hal retrieves more than one keyword response at a time from any
	'of the databases. We start by restoring the pronouns into the user's sentence again:
	UserSentence = SaveUserSentence
	'Now we establish a special sentence on which we can restore ordinary capitalization:
	SpecialSent = UserSentence
	SpecialSent = HalBrain.FixCaps(SpecialSent)
	'Now we add in our spaces and restore ending punctuation to match the user's original sentence:
	If InStr(OriginalSentence, ".") > 0 Then SpecialSent = Replace(" " & SpecialSent & " ", ".", ".", 1, -1, vbTextCompare)
	If InStr(OriginalSentence, "?") > 0 Then SpecialSent = Replace(" " & SpecialSent & " ", ".", "?", 1, -1, vbTextCompare)
	If InStr(OriginalSentence, "!") > 0 Then SpecialSent = Replace(" " & SpecialSent & " ", ".", "!", 1, -1, vbTextCompare)
	'If there were no pronoun reversals required in the sentence,
	'we can recover directly from the original sentence:
	If InStr(UserSentence, " ME") = 0 And InStr(UserSentence, "YOU") = 0 And InStr(UserSentence, "MY ") = 0 And InStr(UserSentence, "YOUR ") = 0 And InStr(UserSentence, "I ") = 0 And InStr(UserSentence, "MINE") = 0 And InStr(UserSentence, "YOURS") = 0 And InStr(UserSentence, "MYSELF") = 0 And InStr(UserSentence, "YOURSELF") = 0 Then SpecialSent = OriginalSentence
	'SAVE FILE USER DEFAULT KEYWORD BRAIN
	'Here we save any information learned in the default user keyword brain file for compatibility.
	If HalBrain.CheckLinkingVerb(UserSentence) = True Then
		LearnKeyword = Replace("" & LearnKeyword & "", " EMAIL ADDRESS ", " EMAIL ", 1, -1, vbTextCompare)
		If Len(LearnKeyword) > 4 And Len(LearnKeyword2) > 4 And BlockSave = False Then
			If LearningLevel > 1 Then HalBrain.AppendFile WorkingDir & Trim(UserName) & "user.brn", """" & LearnKeyword & ""","""","""",""" & SpecialSent & """,""" & Response2 & """,""" & Response3 & """,1,#FALSE#,#FALSE#,""""" & VbCrLf & """" & LearnKeyword2 & ""","""","""",""" & SpecialSent & """,""" & Response2 & """,""" & Response3 & """,1,#FALSE#,#FALSE#,"""""
			DebugInfo = DebugInfo & "Hal has learned new information and has placed it in the file " & Trim(UserName) & "user.brn" & VbCrLf
		End If
		'SAVE FILE USER BACKUP ADDRESS BRAIN
		'Here we save any information learned
		'about numbers and addresses.
		If InStr(OriginalSentence, "ADDRESS") > 0 Then BackupData = True
		If InStr(OriginalSentence, "MAIL") > 0 Then BackupData = True
		If InStr(OriginalSentence, "PHONE") > 0 Then BackupData = True
		If InStr(OriginalSentence, "NUMBER") > 0 Then BackupData = True
		If InStr(OriginalSentence, "address") > 0 Then BackupData = True
		If InStr(OriginalSentence, "mail") > 0 Then BackupData = True
		If InStr(OriginalSentence, "phone") > 0 Then BackupData = True
		If InStr(OriginalSentence, "number") > 0 Then BackupData = True
		If InStr(OriginalSentence, "what is") > 0 Then BackupData = False
		If InStr(OriginalSentence, "where is") > 0 Then BackupData = False
		If BackupData = True Then
			If LearningLevel > 1 Then HalBrain.AppendFile WorkingDir & Trim(UserName) & "user_backup.brn", """" & Left(OriginalSentence, 15) & ""","""","""",""" & SpecialSent & """,""" & Response2 & """,""" & Response3 & """,1,#FALSE#,#FALSE#,"""""
			DebugInfo = DebugInfo & "Hal has learned new information and has placed it in the file " & Trim(UserName) & "user_backup.brn" & VbCrLf
		End If
		'SAVE FILE USER KEYWORD BRAIN 0 1 2
		'Hal now also selects and writes to one of three keyword files at random. The use of
		'these three user keyword files provides more variety of responses when it is not
		'necessary to search for specific factual data. In these files, we only accept words
		'and phrases with a length greater than 9 in order to reduce repetitive-triggering on
		'short common words.
		If Len(LearnKeyword) > 9 And Len(LearnKeyword2) > 9 And BlockSave = False Then
			LearnKeyword_A = Left(LearnKeyword, 20)
			LearnKeyword_B = Left(LearnKeyword2, 20)
			Roulette = Int(Rnd * 3)
			If Roulette = 0 And LearningLevel > 1 Then HalBrain.AppendFile WorkingDir & Trim(UserName) & "user0.brn", """" & LearnKeyword_A & ""","""","""",""" & SpecialSent & """,""" & Response2 & """,""" & Response3 & """,1,#FALSE#,#FALSE#,""""" & VbCrLf & """" & LearnKeyword_B & ""","""","""",""" & SpecialSent & """,""" & Response2 & """,""" & Response3 & """,1,#FALSE#,#FALSE#,"""""
			If Roulette = 1 And LearningLevel > 1 Then HalBrain.AppendFile WorkingDir & Trim(UserName) & "user1.brn", """" & LearnKeyword_A & ""","""","""",""" & SpecialSent & """,""" & Response2 & """,""" & Response3 & """,1,#FALSE#,#FALSE#,""""" & VbCrLf & """" & LearnKeyword_B & ""","""","""",""" & SpecialSent & """,""" & Response2 & """,""" & Response3 & """,1,#FALSE#,#FALSE#,"""""
			If Roulette = 2 And LearningLevel > 1 Then HalBrain.AppendFile WorkingDir & Trim(UserName) & "user2.brn", """" & LearnKeyword_A & ""","""","""",""" & SpecialSent & """,""" & Response2 & """,""" & Response3 & """,1,#FALSE#,#FALSE#,""""" & VbCrLf & """" & LearnKeyword_B & ""","""","""",""" & SpecialSent & """,""" & Response2 & """,""" & Response3 & """,1,#FALSE#,#FALSE#,"""""
			DebugInfo = DebugInfo & "Hal has learned new information and has placed it in the file " & Trim(UserName) & "user" & Roulette & ".brn" & VbCrLf
		End If
	End If

	'RESPOND: PHRASE MAKER COMMENT AND QUESTION GENERATOR
	'If no response is found yet, try an auxiliary keyword file that generates questions
	'from phrases from the user's current sentence.
	GetResponse = HalBrain.HalFormat(GetResponse)
'=vonsmith= Added GetResponseBlock
	If Len(GetResponse) < 4 And GetResponseBlock <> True Then
		KeyBrain = HalBrain.KeywordBrain(UserSentence, WorkingDir & "phrase_detector.brn", False)
		If Len(KeyBrain) > 1 And Len(KeyBrain) < 60 Then
			GetResponse = GetResponse & Replace(HalBrain.ChooseSentenceFromFile(WorkingDir & "phrasemaker.Brn"), "<KeyBrain>", KeyBrain, 1, -1, vbTextCompare)
			DebugInfo = DebugInfo & "The phrase_detector.brn keyword brain has come up with a response: " & GetResponse & VbCrLf
		End If
	End If

 	'SAVE: NOUN WORDS 
	'Hal attempts to save noun words for future use.
	GetResponse = HalBrain.HalFormat(GetResponse) 
	Nounwords = HalBrain.KeywordBrain(UserSentence, WorkingDir & "Nouns_detector.brn", False) 
	Nounwords = HalBrain.HalFormat(Nounwords)
    Disqualify = False
	If HalBrain.TopicSearch(Nounwords, WorkingDir & "disqualify1.brn") = "True" Then Disqualify = True
	If HalBrain.TopicSearch(UserSentence, WorkingDir & "disqualify2.brn") = "True" Then Disqualify = True
    Nounwords = Trim(Nounwords)
    Nounwords = Trim(HalBrain.ProcessSubstitutions(Nounwords, WorkingDir & "extract1.brn"))
    If HalBrain.CountInstances(" ", NounWords) > 0 Then Disqualify = True
    If Len(Nounwords) > 4 And Len(Nounwords) < 12 And Disqualify = False And BlockSave = False And LearningLevel > 1 Then 
    	HalBrain.AppendFile WorkingDir & "random_subject.brn", " " & Nounwords & " "                                                
    	HalBrain.AppendFile WorkingDir & "assoc_subject.brn", "@" & Nounwords & VbCrLf & " " & UCase(Nounwords)
    	DebugInfo = DebugInfo & "Hal has learned a new noun and stored it in his noun files: " & Nounwords & VbCrLf
    End If		
       
   'SAVE: ADJECTIVE WORDS AND PHRASES
   'Hal attempts to save adjective words and phrases for future use.
	GetResponse = HalBrain.HalFormat(GetResponse)
	AdjectiveWords = HalBrain.KeywordBrain(UserSentence, WorkingDir & "Adjectives_detector.brn", False)
	AdjectiveWords = HalBrain.HalFormat(AdjectiveWords)
	Disqualify = False
	If HalBrain.TopicSearch(UserSentence, WorkingDir & "disqualify4.brn") = "True" Then Disqualify = True
	If HalBrain.TopicSearch(AdjectiveWords, WorkingDir & "disqualify3.brn") = "True" Then Disqualify = True
	AdjectiveWords = HalBrain.HalFormat(AdjectiveWords)
	AdjectiveWords = UCase(AdjectiveWords)
	AdjectiveWords = HalBrain.ProcessSubstitutions(AdjectiveWords, WorkingDir & "extract3.brn")
	AdjectiveWords = HalBrain.HalFormat(AdjectiveWords)
	If HalBrain.CountInstances(" ", AdjectiveWords) > 2 Then Disqualify = True
	If Len(AdjectiveWords) > 3 And Len(AdjectiveWords) < 19 And Disqualify = False And BlockSave = False Then
		If LearningLevel > 1 Then HalBrain.AppendFile WorkingDir & "random_adjective.brn", "" & AdjectiveWords & ""
		If LearningLevel > 1 Then HalBrain.AppendFile WorkingDir & "assoc_adjective.brn", "@" & AdjectiveWords & VbCrLf & AdjectiveWords
		DebugInfo = DebugInfo & "Hal has learned a new adjective and stored it in his adjective files: " & AdjectiveWords & VbCrLf
	End If

   'SAVE: WORDS THAT ARE "MY" TO HAL
   'Hal attempts to save words about himself for future use.
	GetResponse = HalBrain.HalFormat(GetResponse)
	MyWords = HalBrain.KeywordBrain(UserSentence, WorkingDir & "My_detector.brn", False)
	MyWords = HalBrain.HalFormat(MyWords)
	Disqualify = False
	If HalBrain.TopicSearch(MyWords, WorkingDir & "disqualify3.brn") = "True" Then Disqualify = True
	MyWords = HalBrain.HalFormat(MyWords)
	MyWords = UCase(MyWords)
	MyWords = HalBrain.HalFormat(MyWords)
    MyWordsKey = UCase(Replace("" & MyWords & "", "MY", "", 1, -1, vbTextCompare) )
    MyWords = Trim(HalBrain.AlphaNumericalOnly(MyWords))
    MyWordsKey = Trim(HalBrain.AlphaNumericalOnly(MyWordsKey))
    If HalBrain.CountInstances(" ", MyWords) > 0 Then Disqualify = True
	If Len(MyWords) > 3 And Len(MyWords) < 19 And Disqualify = False And LearningLevel > 1 And BlockSave = False Then
        HalBrain.AppendFile WorkingDir & "random_MyWords.brn", "" & MyWords & "" 
        HalBrain.AppendFile WorkingDir & "assoc_MyWords.brn", "@" & MyWords & VbCrLf & " " & MyWordsKey
		DebugInfo = DebugInfo & "Hal has learned a new 'my' word and stored it in his mywords files: " & MyWords & VbCrLf
	End If

   'SAVE: WORDS THAT ARE "YOUR" TO THE USER 
   'Hal attempts to save words about the user for future use.
	GetResponse = HalBrain.HalFormat(GetResponse) 
	YourWords = HalBrain.KeywordBrain(UserSentence, WorkingDir & "Your_detector.brn", False) 
	YourWords = HalBrain.HalFormat(YourWords)
    Disqualify = False
    If HalBrain.TopicSearch(MyWords, WorkingDir & "disqualify3.brn") = "True" Then Disqualify = True
    YourWords = HalBrain.HalFormat(YourWords)
    YourWords = Trim(HalBrain.ProcessSubstitutions(YourWords, WorkingDir & "extract5.brn"))
    If HalBrain.CountInstances(" ", YourWords) > 0 Then Disqualify = True
    If Len(YourWords) > 3 And Len(YourWords) < 19 And Disqualify = False And LearningLevel > 1 And BlockSave = False Then 
    	HalBrain.AppendFile WorkingDir & "random_YourWords.brn", "" & YourWords & "" 
    	HalBrain.AppendFile WorkingDir & "assoc_YourWords.brn", "@" & YourWords & VbCrLf & " " & UCase(YourWords)
    	DebugInfo = DebugInfo & "Hal has learned a new 'your' word and stored it in his yourwords files: " & YourWords & VbCrLf
    End If 

	'RESPOND: HAL'S POSITIVE TOPIC ASSOCIATIONS
	If Len(GetResponse) < 4 And GetResponseBlock <> True Then
	    NiceFeeling = HalBrain.ChooseSentenceFromFile(WorkingDir & "random_14pos_action_phrases.brn")
	 	NiceThings = HalBrain.ChooseSentenceFromFile(WorkingDir & "random_15pos_object_phrases.brn")
   		If Rnd * 100 > 65 Then
   			GetResponse = " " & NiceFeeling & " " & NiceThings & " "
			DebugInfo = DebugInfo & "Hal has responded with a positive topic association: " & GetResponse & VbCrLf
   		End If
	End If


	'RESPOND: YES OR NO RESPONSES
	'=vonsmith= This function has been moved toward the top.


	'RESPOND: ZABAWARE KEYWORD BRAIN PRIORITIES 2 3 4
	'If no Response is found yet, try a lower priority keyword match
	'in the Enhanced Main brn file.
	Spinner = Int(Rnd * 400)
	GetResponse = HalBrain.HalFormat(GetResponse)
'=vonsmith= Added GetResponseBlock.
	If Len(GetResponse) < 4 And Spinner < 200 And GetResponseBlock <> True Then
		KeyBrain = HalBrain.KeywordBrain(UserSentence, WorkingDir & "Enhanced_Main.brn", False)
		If Len(KeyBrain) > 3 Then
			GetResponse = KeyBrain & VbCrLf
			DebugInfo = DebugInfo & "Hal has responded using a lower priority keyword match in enhanced_main.brn: " & KeyBrain & VbCrLf
		End If
	End If

	'RESPOND: Use the highest relevance response from the database functions
	GetResponse = HalBrain.HalFormat(GetResponse)
	DebugInfo = DebugInfo & "The highest relevance responsee has a rating of " & HighestRel & " and is """ & HighestRelResponse & """ "
'=vonsmith= Added GetResponseBlock.
	If ((Len(GetResponse) < 4 And Rnd * 100 < 60) And (HighestRel > 5 And HighestRelResponse <> "")) Or ((Rnd * 100 > 90) And (HighestRel > 12 And HighestRelResponse <> "") And HalGreeting = "" And GetResponseBlock <> True) Then
		DebugInfo = DebugInfo & "Hal has decided to use this sentence instead of the response currently in memory, which was: " & GetResponse & VbCrLf
		GetResponse = HighestRelResponse
	Else
		DebugInfo = DebugInfo & "Hal will not use this sentence in place of the currently response in memory. " & VbCrLf
	End If                   
	
'=vonsmith= Disable for now. Answers sound peculiar. Rewrite at a future date.
'    'RESPOND: User asks a general opinion question.
'    If HalBrain.TopicSearch(UserSentence, WorkingDir & "opiniondetect.brn") = "True" Then GenOpinion = True
'	'Note that the following string matches must occur at the sentence beginning only:
'	Roulette = Int(Rnd * 100)
'	If Roulette > 50 Then 
'	If InStr(Trim(UCase(UserSentence)), "WHY ") = 1 Then GenOpinion = True
'    	If InStr(Trim(UCase(UserSentence)), "WHAT ") = 1 Then GenOpinion = True
'    	If InStr(Trim(UCase(UserSentence)), "WHEN ") = 1 Then GenOpinion = True
'    	If InStr(Trim(UCase(UserSentence)), "HOW ") = 1 Then GenOpinion = True
'    	If InStr(Trim(UCase(UserSentence)), "WHO ") = 1 Then GenOpinion = True
'    	If InStr(Trim(UCase(UserSentence)), "WHERE ") = 1 Then GenOpinion = True
'	End If
'	If GenOpinion = True And OrigBrain = "" Then
'    	If Rnd * 100 > 25 Then RepeatQuest = UserSentence & " ? "
'		If Rnd * 100 > 50 Then PreAmble = HalBrain.ChooseSentenceFromFile(WorkingDir & "preamble.brn")
'		Recommend = HalBrain.ChooseSentenceFromFile(WorkingDir & "recommend.brn")
'    	GetResponse = RepeatQuest & " " & PreAmble & " " & Recommend & GetResponse
'    	DebugInfo = DebugInfo & "Hal has responded to a general opinion question." & vbCrLf			
'    End If
    
	'RESPOND: CALL MAKETALK FUNCTION
	'This function assembles sentences from components.
	GetResponse = HalBrain.HalFormat(GetResponse)
	If Len(GetResponse) < 4 And Rnd * 300 < 100 And GetResponseBlock <> True Then
		GetResponse = HalBrain.SentenceGenerator(WorkingDir & "sentgen.brn")
		DebugInfo = DebugInfo & "Hal has responded using the sentgen.brn file: " & GetResponse & VbCrLf
	End If

	'RESPOND: USE RANDOM QUESTION COLLECTED FROM USER
	'If Hal has not found a response yet, he will randomly select a
	'question once posed by the user in order to find something to say.
	'If the user answers the question, then Hal will know that answer
	'in the future. For variety, we make triggering of this response
	'dependent on a random number.
	Spinner = Int(Rnd * 700)
	GetResponse = HalBrain.HalFormat(GetResponse)
	If Len(GetResponse) < 4 And Spinner < 350 And GetResponseBlock <> True Then
	   	GetResponse = HalBrain.ChooseSentenceFromFile(WorkingDir & Trim(UserName) & "user_question.brn")
		DebugInfo = DebugInfo & "Hal has responded using user_question.brn file: " & GetResponse & VbCrLf
	End If

	'RESPOND: USER EXPRESSES AN EITHER-OR, OR MULTIPLE CHOICE
	If InStr(UserSentence, " OR ") > 0 Then MustChoose = True
	If InStr(UserSentence, " EITHER ") > 0 Then MustChoose = True
	If InStr(UserSentence, " CHOOSE ") > 0 Then MustChoose = True
	If InStr(UserSentence, " CHOICE ") > 0 Then MustChoose = True
	If InStr(UserSentence, " ALTERNATIVE ") > 0 Then MustChoose = True
	If InStr(UserSentence, " VERSUS ") > 0 Then MustChoose = True
	If InStr(UserSentence, " VS ") > 0 Then MustChoose = True
	If Len(UserSentence) < 10 Then MustChoose = False
	If MustChoose = True And NoChoosing = False And GetResponseBlock <> True Then
		GetResponse = HalBrain.ChooseSentenceFromFile(WorkingDir & "choice.brn") & " " & GetResponse
 		If Rnd * 100 > 50 Then GetResponse = Replace(GetResponse, "<MaybeName>", "<UserName>", 1, -1, vbTextCompare)
 		GetResponse = Replace(GetResponse, "<MaybeName>", "", 1, -1, vbTextCompare)
		DebugInfo = DebugInfo & "Hal has responded to an either-or question: " & GetResponse & VbCrLf
	End If

	'PROCESS: RECORD TIME
	'Record the current time, so Hal knows the time in between sentences.
	LastResponseTime = Now

	'SAVE: FILE HAL/USER SENTENCE ASSOCIATIONS
	'If the user seems to be continuing a line of thought
	'from something Hal just said, Hal associates words
	'from Hal's previous statement with the user's sentence
	'and stores the resulting association in a special user sentence file.
	Responding = False
    If IsQuestion(PrevSent) = True Then Responding = True
'ORIG	If InStr(PrevSent, "?") > 0 Then Responding = True
	If InStr(OriginalSentence, "!") > 0 Then Responding = True
	If HalBrain.TopicSearch(UserSentence, WorkingDir & "Responding.brn") = "True" Then Responding = True
'=vonsmith= Added BlockSave.
	If Responding = True And BlockSave <> True Then
		PrevSent = HalBrain.AlphaNumericalOnly(PrevSent)
		PrevSent = UCase(PrevSent)
		AnswerSent = "@" & Trim(SpecialSent)
		QuestionSent = " " & Trim(HalBrain.ExtractKeywords(PrevSent))
		If HalBrain.CountInstances(" ", QuestionSent) > 3 And Len(AnswerSent) > 8 And Len(QuestionSent) > 8 And InStr(1, AnswerSent, " ", vbTextCompare) > 0 And BlockSave = False Then
			If Learninglevel > 1 Then HalBrain.AppendFile WorkingDir & Trim(UserName) & "convresp.brn", AnswerSent & VbCrLf & QuestionSent
		End If
	End If

	'SAVE: FILE USER STRINGS
	'This routine saves the users response. Later a function will extract 15-character strings
	'from the beginning, end, and middle of the user's remark for possible later response.
	UserSentence = " " & Trim(UserSentence) & " "
'=vonsmith= Added BlockSave. Don't save user strings if ComputerName has been detected in OriginalSentence earlier.
	If Len(UserSentence) > 20 And Len(UserSentence) < 90 Then
		If (Learninglevel > 1 And BlockSave <> True) Then HalBrain.AppendFile WorkingDir & Trim(UserName) & "user_strings.brn", " " & Trim(SpecialSent)
'		If Learninglevel > 1 Then HalBrain.AppendFile WorkingDir & Trim(UserName) & "user_strings.brn", " " & Trim(SpecialSent)
	End If

	'SAVE: FILE USER SENTENCE DEFAULT
	'Unless the user seems to be asking for data recall, Hal always adds
	'to the default brain user sentence file an association of the current
	'user sentence With words selected from that same current user sentence.
	If InStr(UserSentence, "WHAT IS") = 0 And Responding = False Then
		AnswerSent = "@" & Trim(SpecialSent)
		QuestionSent = " " & Trim(HalBrain.ExtractKeywords(UserSentence))
		If HalBrain.CountInstances(" ", QuestionSent) > 3 And Len(AnswerSent) > 8 And Len(QuestionSent) > 8 And InStr(1, AnswerSent, " ", vbTextCompare) > 0 Then
		  	If (LearningLevel > 1 And BlockSave <> True) Then HalBrain.AppendFile WorkingDir & Trim(UserName) & "usersent.brn", AnswerSent & VbCrLf & QuestionSent
'		  	If LearningLevel > 1 Then HalBrain.AppendFile WorkingDir & Trim(UserName) & "usersent.brn", AnswerSent & vbCrLf & QuestionSent
		End If
	End If

	'SAVE: FILE SHARED USER SENTENCES
	'Unless the user seems to be asking for data recall, or talking about
	'himself or herself, Hal adds to a shared user sentence file. This allows
	'Hal to gain knowledge that he can apply to conversations with multiple users.
'=vonsmith= Add improved pronoun detection.
    If Responding = False And InStr(UserSentence, "WHAT IS") = 0 And HalBrain.TopicSearch(UserSentence, WorkingDir & "XTF_SYS_PronounDetect.brn") = "" Then
'	If Responding = False And InStr(UserSentence, "WHAT IS") = 0 And InStr(UserSentence, " YOU ") = 0 And InStr(UserSentence, " YOU'") = 0 And InStr(UserSentence, " YOUR ") = 0 And InStr(UserSentence, " YOURS ") = 0 And InStr(UserSentence, " YOURSELF ") = 0 And InStr(UserSentence, " WE ") = 0 And InStr(UserSentence, " US ") = 0 And InStr(UserSentence, " OUR ") = 0 And InStr(UserSentence, " I ") = 0 And InStr(UserSentence, " ME ") = 0 And InStr(UserSentence, " MY ") = 0 And InStr(UserSentence, " MINE ") = 0 And InStr(UserSentence, " MYSELF ") = 0 And InStr(UserSentence, " I' ") = 0 Then
		AnswerSent = "@" & Trim(SpecialSent)
		QuestionSent = " " & Trim(HalBrain.ExtractKeywords(UserSentence))
		If HalBrain.CountInstances(" ", QuestionSent) > 3 And Len(AnswerSent) > 8 And Len(QuestionSent) > 8 And InStr(1, AnswerSent, " ", vbTextCompare) > 0 And BlockSave = False Then
		  	If (LearningLevel > 1  And BlockSave <> True) Then HalBrain.AppendFile WorkingDir & "shared_usersent.brn", AnswerSent & VbCrLf & QuestionSent
'		  	If LearningLevel > 1 Then HalBrain.AppendFile WorkingDir & "shared_usersent.brn", AnswerSent & vbCrLf & QuestionSent
		End If
	End If

	'SAVE: FILE ADDRESS AND NUMBER BACKUP
	'Unless the user seems to be asking for data recall, Hal will also put
	'sentences that have to do with addresses and numbers into a special
	'user recall file that adds a backup source for factual data.
	If InStr(Trim(UserSentence), "WHAT IS ") = 0 And InStr(UserSentence, "ADDRESS") > 0 Or InStr(UserSentence, "NUMBER") > 0 Then
'=vonsmith= If InStr(UserSentence, "WHAT IS") = 0 And InStr(UserSentence, "ADDRESS") > 0 Or InStr(UserSentence, "NUMBER") > 0 Then
		AnswerSent = "@" & Trim(SpecialSent)
		QuestionSent = " " & Trim(HalBrain.ExtractKeywords(UserSentence))
		If HalBrain.CountInstances(" ", QuestionSent) > 2 And Len(AnswerSent) > 8 And Len(QuestionSent) > 8 And InStr(1, AnswerSent, " ", vbTextCompare) > 0 Then
		  	If (LearningLevel > 1 And BlockSave <> True) Then HalBrain.AppendFile WorkingDir & Trim(UserName) & "user_recall.brn", AnswerSent & VbCrLf & QuestionSent
'		  	If LearningLevel > 1 Then HalBrain.AppendFile WorkingDir & Trim(UserName) & "user_recall.brn", AnswerSent & vbCrLf & QuestionSent
		End If
	End If

	'SAVE TOPIC SENTENCE IN APPROPRIATE FILE IF CURRENTLY IN TOPICFOCUS MODE
'=vonsmith= Use XTF Topic method instead.

	'RESPOND: USER DEFAULT USER KEYWORD BRAIN (QUALIFIED)
	'If the user seems to be asking for recall of specific information Hal
	'needs to check the file where addresses and numbers might be stored. If
	'our keyword requirements are met, we direct the user's inquiry to the
	'default user keyword file that is used with other brain plug-ins to
	'maintain compatibility with previous files the user may have created. 
	If InStr(UserSentence, "CAPITAL") = 0 And InStr(UserSentence, "WHAT IS") > 0 And InStr(UserSentence, "WHAT IS NEW ") = 0 Or InStr(UserSentence, "MAIL") > 0 Or InStr(UserSentence, "ADDRESS") > 0 Or InStr(UserSentence, "NUMBER") > 0 Then
		KeyBrain = HalBrain.KeywordBrain(UserSentence, WorkingDir & Trim(UserName) & "user.brn", False)
'=vonsmith= Added GetResponseBlock.
		If Len(KeyBrain) > 3 And GetResponseBlock <> True Then
			GetResponse = KeyBrain & VbCrLf
			DebugInfo = DebugInfo & "Hal has responded using the USER DEFAULT USER KEYWORD BRAIN (QUALIFIED): " & KeyBrain & VbCrLf
		End If
	End If

	'RESPOND: USER BACKUP BRAIN (QUALIFIED)
	'If the user seems to be asking for recall of specific information Hal
	'needs to check the file where addresses and numbers might be stored.
	'If our keyword requirements are met, we direct the user's inquiry to
	'the backup user keyword file.
	If InStr(UserSentence, "WHAT") > 0 Then AskData = True
	If InStr(UserSentence, "WHERE") > 0 Then AskData = True
	If InStr(UserSentence, "EMAIL") > 0 Then AskData = True
	If InStr(UserSentence, "SEND") > 0 Then AskData = True
	If InStr(UserSentence, "MAIL") > 0 Then WantsData = True
	If InStr(UserSentence, "ADDRESS") > 0 Then WantsData = True
	If InStr(UserSentence, "NUMBER") > 0 Then WantsData = True
'=vonsmith= Added GetResponseBlock.
	If AskData = True And WantsData = True And GetResponseBlock <> True Then
		KeyBrain = HalBrain.KeywordBrain(UserSentence, WorkingDir & Trim(UserName) & "user_backup.brn", False)
		If Len(KeyBrain) > 3 Then GetResponse = KeyBrain & VbCrLf
		KeyBrain = HalBrain.KeywordBrain(UserSentence, WorkingDir & Trim(UserName) & "user.brn", False)
		If Len(KeyBrain) > 3 Then GetResponse = GetResponse & " Right <UserName>? " & KeyBrain & " ! " & VbCrLf
		DebugInfo = DebugInfo & "Hal has responded using the USER BACKUP BRAIN (QUALIFIED): " & GetResponse & VbCrLf
	End If

	'SAVE: FILE QUESTIONS IN RANDOM QUESTION RETRIEVAL FILE
	'Hal saves the user's questions (with pronouns reversed)
	'so that he can pose questions back to the user later for 3 purposes:
	'1. If the user answers a question later, Hal will learn the answer.
	'2. It adds variety to future conversations for the user.
	'3. It gives Hal another possible response when "stuck" for an answer.
	QuestionLength = HalBrain.HalFormat(SpecialSent)
	If InStr(1, SpecialSent, "?", vbTextCompare) > 0 Then GoodQuest = True
	If InStr(1, SpecialSent, "Who ", vbTextCompare) > 0 Then GoodQuest = True
	If InStr(1, SpecialSent, "What ", vbTextCompare) > 0 Then GoodQuest = True
	If InStr(1, SpecialSent, "When ", vbTextCompare) > 0 Then GoodQuest = True
	If InStr(1, SpecialSent, "Where ", vbTextCompare) > 0 Then GoodQuest = True
	If InStr(1, SpecialSent, "Why ", vbTextCompare) > 0 Then GoodQuest = True
	If InStr(1, SpecialSent, "How ", vbTextCompare) > 0 Then GoodQuest = True
	If InStr(1, SpecialSent, ".", vbTextCompare) > 0 Then GoodQuest = False
	If InStr(1, SpecialSent, "!", vbTextCompare) > 0 Then GoodQuest = False
	If InStr(1, SpecialSent, " am I ", vbTextCompare) > 0 Then GoodQuest = False
	If Len(QuestionLength) < 15 Then GoodQuest = False
	If GoodQuest = True And BlockSave = False And LearningLevel > 1 Then HalBrain.AppendFile WorkingDir & Trim(UserName) & "user_question.brn", SpecialSent & VbCrLf & SpecialSent


'=vonsmith= Increased allowable file size.
	'POST PROCESS: LIMIT FILE SIZE
	'We want to make sure the sentence files
	'don't get too big so we limit them.
	HalBrain.LimitSize WorkingDir & "shared_usersent.brn", 4000000
	HalBrain.LimitSize WorkingDir & Trim(UserName) & "convresp.brn", 4000000
	HalBrain.LimitSize WorkingDir & Trim(UserName) & "user0.brn", 4000000
	HalBrain.LimitSize WorkingDir & Trim(UserName) & "user1.brn", 4000000
	HalBrain.LimitSize WorkingDir & Trim(UserName) & "user2.brn", 4000000
	HalBrain.LimitSize WorkingDir & Trim(UserName) & "usersent.brn", 4000000
	HalBrain.LimitSize WorkingDir & Trim(UserName) & "user_question.brn", 4000000
	HalBrain.LimitSize WorkingDir & Trim(UserName) & "user_strings.brn", 4000000


	'RESPOND: HAL NOTICES HE IS REPEATING HIMSELF
	'Hal may make a comment or alter his remark
	'if he detects himself being repetitious.
	If HalBrain.CheckRepetition(GetResponse, PrevSent) = True And GetResponseBlock <> True Then
		RepeatResponse = HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_HalRepeat.brn")
		GetResponse = Replace(RepeatResponse, "<response>", GetResponse, 1, -1, vbTextCompare)
		DebugInfo = DebugInfo & "Hal has noticed he is repeating himself and has made a comment about it: " & GetResponse & VbCrLf
	End If

	'RESPOND: MAKE COMMENTS ABOUT SHORT PHRASES
	GetResponse = GetResponse & ShortPhrase


'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'In Ultra Hal Assistant v5.0 the "RESPOND: MAKE COMMENTS ABOUT SHORT PHRASES"
' function should precede this function.

'PROCESS: REVERSE CERTAIN CONTRACTIONS, OTHER SUBSTITUTIONS AND CAPITALIZATION - PART II OF II
'This version is rewritten by =vonsmith=, version 02-14-04a which splits this function into two
'parts; Part I - Processes the user's request to capitalize words or phrase and Part II - That
'post-processes the substitions. Part I is located toward the top of this script.
'Version 01-15-04a is an update to version 11-10-03a which adds checking for empty arrays and
'prevent error messages.
'Version 11-10-03a is an update to version 11-19-03a which changes the file name used from
'Corrections.brn to XTF_SYS_Corrections.brn.
'
'This function improves on the original function in Ultra Hal Assistant v5.0 and
'provides new capability.
'
'ORIGINAL CAPABILITY:
'Standardizing on contractions can make Hal sound conversational.
'However, certain sentence constructions don't work well if expressed as
'contractions.  For example:
'"I don't know where it is" becomes "I don't know where it's."
'For another example, "That's how he is" becomes "That's how he's."
'To solve these types of cases we attempt to modify certain contractions, words,
'and phrases at the end of this function, now that Hal's thinking is done.
'
'ADDITIONAL CAPABILITIES:
'Normally Hal converts every user input into all caps to evaluate the sentence
'and create a response. However if Hal parrots back the user input the user's
'capitalization is lost. Example:
'  User: Where is Disneyland?  Hal: Where is disneyland? We must examine this.
'Capitals in names of people and places are lost similarly.
'  User: Do you know Ted and Mark?  Hal: Should I know ted and mark?
'The programmer could edit the XTF_SYS_Corrections.brn file to substitute Mark for mark
'in all cases, but this would erroneously lead to:
'  User: How much should I fill a glass?  Hal: Fill it to the Mark.
'
'This rewritten function will preserve the user's capitalized words in the input
'sentence and replace Hal's uncapitalized words in GetResponse with the correct
'user capitalized versions. Example:
'  User: Where is Ted and Mark?  Hal: I don't know Ted and Mark.
'Hal now takes a clue from the user about capitalization.
'  User: Where is Ted's mark?  Hal: Ted's mark is not here.
'  User: I know ted and mark.  Hal: Where is ted and mark.
'
'In cases where the user always wants a word capitalized, then Hal can save a
'word to the XTF_SYS_Corrections.brn for the user. Example:
'  User: Hal caps Disneyland.
'  Hal: Your input Disneyland is saved as capitalized in the XTF_SYS_Corrections.brn file.
'If your Hal is named Betty instead type:
'  User: Betty caps Saint Mary.
'  Hal: Your input Saint Mary is saved as capitalized in the XTF_SYS_Corrections.brn file.
'Since Hal's computername appears in the user input this programming type input
'will not be saved to any other brn files or anywhere else in Hal's data base.
'Now for example:
'  User: I hear Saint Mary's bells.  Hal: What is Saint Mary's bells?
'However Hal still takes a clue from the user's input.
'  User: I hear saint mary's bells.  Hal: What is saint mary's bells?
'The phrase "saint mary's" is still lower case even if it is in the XTF_SYS_Corrections.brn
'file. Hal always assumes the user's use of capitalization is correct.
'This method should produce the correct capitalization in almost every case. The
'programmer shouldn't add words like "Mark" or "Hall" to XTF_SYS_Corrections.brn because
'these names can also be used as uncapitalized words. However words like "Fred",
'"God", "Christmas", "Knott's Berry Farm" can be added with reasonable certainty
'that they should always be capitalized. You can add as many words to
'XTF_SYS_Corrections.brn as you like. Duplicated words will not be added to the file.
'
'This function does not handle all capitalized words like acronyms, i.e., DOA, SUV.
'Unfortunately Hal's other functions do not preserve all cap words during the final
'processing of GetResponse.
'
'Have fun with this improved function. =vonsmith=
'
'P.S. - Try this. User: Where is Mark's mark? See if Hal gets it right.
'
Dim CapWordArray, CapsWord(50), CapArraySize
CapArraySize = 0
CapWordArray = Split(Trim(OriginalSentence), " ", -1, 1)  'WordArray() contains each word in sentence.
If (IsArray(CapWordArray) = True And UBound(CapWordArray) > -1) Then CapArraySize = UBound(CapWordArray)
If CapArraySize > 50 Then CapArraySize = 50  'Limit array size to something manageable.
'Check all words in the user's input and preserve capitalized words in the CapsWord() array.
'Variable 'I' starts at 1 instead of zero and thus ignores the first word in the sentence
' since that will always be capitalized.
CapsCnt = 0
For I = 1 To CapArraySize
   CapWordArray(I) = HalBrain.AlphaNumericalOnly(Trim(CapWordArray(I)))
   LeftChar = Left(CapWordArray(I), 1)
   If Len(LeftChar) = 0 Then LeftChar = " "
   If (Asc(LeftChar) > 64 And Asc(LeftChar) < 91) Then  'Check if first letter is capitalized.
      CapsCnt = CapsCnt + 1
      CapsWord(CapsCnt) = CapWordArray(I)
   End If
Next

'Save capitalization request from user. The user request is detected in Part I of this function.
If UserCapRequest = True And CapWordPos > 0 Then
   CapPhrase = ""
   For I = CapWordPos To CapArraySize  'Format word or phrase.
      CapPhrase = CapPhrase & " " & CapWordArray(I)
   Next
   CapPhrase = Trim(CapPhrase)
   'Check and see if capitalized word has been saved to XTF_SYS_Corrections.brn before. Only save if doesn't exist there.
   If HalBrain.TopicSearch(" " & LCase(CapPhrase) & " ", WorkingDir & "XTF_SYS_Corrections.brn") <> " " & CapPhrase & " " Then
      HalBrain.AppendFile WorkingDir & "XTF_SYS_Corrections.brn", """" & " " & LCase(CapPhrase) & " " & """,""" & " " & CapPhrase & " " & """" & VbCrLf & """" & " " & LCase(CapPhrase) & "'" & """,""" & " " & CapPhrase & "'" & """"
   End If
   GetResponse = "I'll remember to capitalize <quote>" & CapPhrase & "<quote> in the future. "
End If

'HalFormat the GetResponse to clean up a few things before proceeding.	
GetResponse = HalBrain.HalFormat(GetResponse)
'Add spaces to aid word detection for capitalizaton and error correction.
'Excess spaces will be removed by existing Hal functions later.
GetResponse = Replace(GetResponse, ".", " . ", 1, -1, vbTextCompare)
GetResponse = Replace(GetResponse, "?", " ? ", 1, -1, vbTextCompare)
GetResponse = Replace(GetResponse, ",", " , ", 1, -1, vbTextCompare)
GetResponse = Replace(GetResponse, "!", " ! ", 1, -1, vbTextCompare)

'Normalize GetResponse spacing.
GetResponse = " " & Trim(GetResponse) & " "

'Process special cases.
'Changes Hal's odd responses like, "Tell you about dogs." to "I could tell you about dogs."
If InStr(1, GetResponse, " TELL YOU ", vbTextCompare) = 1 Then
GetResponse = Replace(GetResponse, " TELL YOU ", " I COULD TELL YOU ", 1, -1, vbTextCompare)
End If

'Make corrections for capitalization and other errors.
GetResponse = HalBrain.ProcessSubstitutions(GetResponse, WorkingDir & "XTF_SYS_Corrections.brn")

'User knows best. Capitalize words in the GetResponse if user has used that word as upper case.
For I = 1 To CapsCnt
   GetResponse = Replace(GetResponse, " " & LCase(CapsWord(I)) & " ", " " & CapsWord(I) & " ", 1, -1, vbTextCompare)
Next

'User knows best. Uncapitalize words in the GetResponse if user has used that word as lower case.
Dim CappedWord(50)
For I = 1 To CapArraySize
   LeftChar = UCase(Left(CapWordArray(I), 1))
   CappedWord(I) = LeftChar & Mid(CapWordArray(I), 2)
   GetResponse = Replace(GetResponse, " " & CappedWord(I) & " ", " " & CapWordArray(I) & " ", 1, -1, vbBinaryCompare)
Next
'In Ultra Hal Assistant v5.0 the "RESPOND: CHANGE TOPIC" process should follow
' this function.
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


'=vonsmith= Disable for now. Rewrite later.    
	'RESPOND: CHANGE TOPIC
	'If a different procedure has requested that the topic be changed
	'Hal will do so now
'	NewTopic = HalBrain.ChooseSentenceFromFile(WorkingDir & "topic.brn")
'	GetResponse = Replace(GetResponse, "<ChangeSubject>", NewTopic, 1, -1, vbTextCompare)
'	GetResponse = Replace(GetResponse, "<ChangeTopic>", NewTopic, 1, -1, vbTextCompare)
'	GetResponse = Replace(GetResponse, "<NewTopic>", NewTopic, 1, -1, vbTextCompare)
'	GetResponse = Trim(GetResponse)
'	If (GetResponse = "" And GetResponseBlock <> True) Then GetResponse = NewTopic


	'POST PROCESS: SAVE HAL'S RESPONSE
	PrevSent = GetResponse


'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'In Ultra Hal Assistant v5.0 the "POST PROCESS: SAVE HAL'S RESPONSE"
' function should precede this function.
'
'PROCESS: HAL CALLS USER BY NICKNAME - PART II OF II
'(c) 2004 Scott Higgins. Portions of this script are copyright by Scott Higgins, aka: =vonsmith=
'This script shall not be sold or used for any purpose unless specifically authorized by the author
'in writing. Personal (non-business) use of this script is free for users of Ultra Hal Assistant.
'This is an entirely new function written by =vonsmith= , version 11-19-03a.
'Replaces version 11-14-03a. This newer version varies the nickname a bit more if
'"<UserName>" occurs more than once in the GetReponse string.
'
'This is the second part of this function. The first part is located toward the top of this script.
'This function lets the user specify one or more nicknames that the user wishes
'to be called by Hal. The nicknames are stored in a user specific self generated file
'called XTF_SYS_<UserName>UserNickname.brn. If more than one nickname is specified then Hal
'will randomly choose one of the nicknames from the XTF_SYS_<UserName>UserNickname.brn file.
'This is nice if you want Hal to call you "Master" sometimes and at other times "Great One".
'Multiple nicknames are great for creating petnames such as "sweetie", "honey", "dearest", etc.
'If a nickname Is specified Then the default Hal Assistant username will no longer be used
'when Hal speaks to the user, however the default username is still used for assigning
'user filenames and all other normal Hal functions. If the user wants to be called by
'his/her default Hal Assistant username then just add it as a nickname. If the user
'prefers to be called one nickname more often than another then just add that nickname
'multiple times. The more times the user adds a nickname the more likely that nickname
'will be used. The function does not affect any other Hal brain operations or files.
'To get rid of the nicknames delete the XTF_SYS_<UserName>UserNickname.brn file.
Dim PrevNickname, UserNickname
PrevNickname = ""
UserNickname = ""
TestSentence = UserSentence
If InStr(1, GetResponse, "<UserName>", vbTextCompare) > 0 Then
   For X = 0 To 3
      UserNickname = HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_UserNickname(" & Trim(UserName) & ").brn")
'      If StrComp(PrevNickname, Nickname, vbTextCompare) = 0 Then 'If the same name as last time try to get another name.
      If UserNickname = PrevNickname Then  'If the same name as last time try to get another name.
         UserNickname = HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_UserNickname(" & Trim(UserName) & ").brn")
      End If
      If UserNickname <> "" Then GetResponse = Replace(GetResponse, "<UserName>", UserNickname, 1, 1, vbTextCompare)
      PrevNickname = UserNickname
   Next
   GetResponse = Replace(GetResponse, "<UserName>", UserNickname, 1, -1, vbTextCompare) 'Replace any remaining "<UserName>".
End If
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'PROCESS: ADD ? TO HAL'S RESPONSE IF IT IS A QUESTION WITHOUT A ? MARK
'This is an new function written by =vonsmith= , version 02-04-04a.
'Check GetResponse to see if it is a question.
If (IsQuestion(GetResponse) = True And Not InStr(1, GetResponse, "?", vbBinaryCompare) > 0) Then
   GetResponse = Trim(GetResponse)
   If InStr(1, GetResponse, ".", vbBinaryCompare) > 0 Then
      GetResponse = Replace(GetResponse, ".", "?", 1, 1, vbBinaryCompare)
   Else GetResponse = GetResponse & "?"
   End If
End If
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'POST PROCESS: DISPLAY HAL'S MOOD 
'(c) 2004 Scott Higgins. Portions of this script are copyright by Scott Higgins, aka: =vonsmith=
'This script shall not be sold or used for any purpose unless specifically authorized by the author
'in writing. Personal (non-business) use of this script is free for users of Ultra Hal Assistant.
'This is an new function written by =vonsmith= , version 02-04-04a.
'This function temporarily alters Hal's Haptek character's displayed emotion for a few seconds 
'after each response. The variable XTF_Emotion can be set by any preceding emotion sensing function.
If XTF_Emotion <> "" Then
   Select Case XTF_Emotion
      Case "ANGRY1"
         HapFile = "Angry.hap"
      Case "ANGRY2"
         HapFile = "Bully.hap"
      Case "ANGRY3"
         HapFile = "Psycho.hap"
      Case "RUNPROG"
         HapFile = "Happy.hap"
      Case "SNOOZE"
         HapFile = "Sleepy.hap"
      Case "WRITE"
         HapFile = "Happy.hap"
      Case "LEARN"
         HapFile = "Happy.hap"
      Case "HAPPY1"
         HapFile = "Happy.hap"
      Case "HAPPY2"
         HapFile = "ShyLove.hap"
      Case "SAD1"
         HapFile = "Sad.hap"
      Case "SAD2"
         HapFile = "Mellow.hap"
      Case "SAD3"
         HapFile = "Brokenheart.hap"
      Case "SURPRISED1"
         HapFile = "Pondering.hap"
      Case "SURPRISED2"
         HapFile = "Skeptic.hap"
      Case "NORMAL1"
         HapFile = "Neutral.hap"
      Case "NORMAL2"
         HapFile = "Shy.hap"
      Case "NORMAL3"
         HapFile = "ShyLove.hap"
      Case "SILLYFACE1"
         HapFile = "XTF_SillyFace1.hap"
      Case "SILLYFACE2"
         HapFile = "XTF_SillyFace2.hap"
      Case "SILLYFACE3"
         HapFile = "XTF_SillyFace3.hap"
      Case Else   
   End Select
   HalCommands = "<HAPFILE>" & HapFile & "</HAPFILE>"
   XTF_Emotion = ""
End If
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x

    
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'POST PROCESS: CONVERT WORDS TO CONTRACTIONS
'Convert words to contractions for a more natural sounding response.
GetResponse = Replace("" & GetResponse & " ", " I AM ", " I'M ", 1, -1, vbTextCompare)
GetResponse = Replace("" & GetResponse & " ", " WILL NOT ", " WON'T ", 1, -1, vbTextCompare)
GetResponse = Replace("" & GetResponse & " ", "OULD NOT ", "OULDN'T ", 1, -1, vbTextCompare)
GetResponse = Replace("" & GetResponse & " ", " CAN NOT ", " CAN'T ", 1, -1, vbTextCompare)
GetResponse = Replace("" & GetResponse & " ", " YOU ARE ", " YOU'RE ", 1, -1, vbTextCompare)
GetResponse = Replace("" & GetResponse & " ", " ARE NOT ", " AREN'T ", 1, -1, vbTextCompare)
GetResponse = Replace("" & GetResponse & " ", " DOES NOT ", " DOESN'T ", 1, -1, vbTextCompare)
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x

  
	'POST PROCESS: PRESERVE ALL VARIABLES
	'Remember all the variables through encoding them into one function string using 
	'the DLL, since for some reason ByRef assignments don't work when a Visual Basic
	'executable is calling a function in a VBScript program.
	PrevUserSent = UserSentence 
	GetResponse = HalBrain.FixCaps(HalBrain.HalFormat(GetResponse))


'=vonsmith= We encode all the custom variables back into the CustomMem variable.
CustomMem = EncodeVar(QuestionPending, "QuestionPending") & EncodeVar(RelPrevTopic, "RelPrevTopic") & EncodeVar(RelPrevTopicPlural, "RelPrevTopicPlural") & EncodeVar(PrevTopicPlural, "PrevTopicPlural") & EncodeVar(RelDetailTopicPlural, "RelDetailTopicPlural") & EncodeVar(RelDetailTopicSingular, "RelDetailTopicSingular") & EncodeVar(RelBaseTopicPlural, "RelBaseTopicPlural") & EncodeVar(RelBaseTopicSingular, "RelBaseTopicSingular") & EncodeVar(MakeFaceCount, "MakeFaceCount") & EncodeVar(DB, "DB") & EncodeVar(DBXTF, "DBXTF") & EncodeVar(DBTOPIC, "DBTOPIC") & EncodeVar(Nickname, "Nickname")


'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x                                              
'POST PROCESS: PERFORM DEBUG FUNCTIONS
'(c) 2004 Scott Higgins. Portions of this script are copyright by Scott Higgins, aka: =vonsmith=
'This script shall not be sold or used for any purpose unless specifically authorized by the author
'in writing. Personal (non-business) use of this script is free for users of Ultra Hal Assistant.
'This is an entirely new function written by =vonsmith= , version 02-11-03a.
'
'This function supports the classic (original) debugmode function and has additional debug
'functions with new capability. In selected cases the debug will be written to a text log
'file for later analysis. Some modes are latched and will continue to run on every conversation
'cycle. The user must beware that text log files, if left latched on, can build huge files.
'This function could be written in a more condensed form, but its current format will allow
'easy expansion for future functionality.

'Classic DebugMode Support. Transfer functionality to Select Case DB = 1.
If DebugMode = True Then DB = 1

'Enhanced debug functions. 
If (DB <> 0 Or DBXTF <> 0 Or DBTOPIC <> 0) Then
   Select Case DB
      Case 1
         'Original mode, write to screen, once only.
         GetResponse = GetResponse & VbCrLf & "<" & DebugInfo & ">"         
      Case 2
         'Original mode, write to screen, latched on.
         GetResponse = GetResponse & VbCrLf & "<" & DebugInfo & ">"         
      Case 3
         'Original mode, writes to screen and to file, latched on.
         GetResponse = GetResponse & VbCrLf & "<" & DebugInfo & ">"         
         DebugInfoFile = "START =========== XTF DB DEBUG LOG =========== START" & VbCrLf & "Log Time: " & Now & VbCrLf & VbCrLf & "GetResponse: " & GetResponse & VbCrLf & VbCrLf & "END ------------- XTF DB DEBUG LOG ------------- END" & VbCrLf & VbCrLf & VbCrLf
         HalBrain.AppendFile WorkingDir & "Z_XTF_DB_LOG.TXT", DebugInfoFile                                                                                           
         DebugInfo = ""
   End Select

   Select Case DBXTF
      Case 1
         'Write XTF Topic data to file, once only.
         HalBrain.AppendFile WorkingDir & "Z_XTF_DEBUG_LOG.TXT", DebugText
      Case 2
         'Write XTF Topic data to file, latched on.         
         HalBrain.AppendFile WorkingDir & "Z_XTF_DEBUG_LOG.TXT", DebugText
   End Select
 
   Select Case DBTOPIC
      Case 1
         'Write current topic to screen, once only.
         GetResponse = GetResponse & "<currtopic:" & CurrTopic & ">"
      Case 2
         'Write current topic to screen, latched on.
         GetResponse = GetResponse & "<currtopic:" & CurrTopic & ">"         
   End Select
End If
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x

       
GetResponse = GetResponse & HalBrain.StoreVars(HalCommands, Hate, Swear, Insults, Compliment, PrevSent, LastResponseTime, PrevUserSent, CustomMem, GainControl, PrevTopic)
'ORIG: GetResponse = GetResponse & HalBrain.StoreVars(HalCommands, Hate, Swear, Insults, Compliment, PrevSent, LastResponseTime, PrevUserSent, CustomMem, GainControl, TopicFocus)

End Function
'==========================END OF GETRESPONSE FUNCTION==========================
'==========================END OF GETRESPONSE FUNCTION==========================
'==========================END OF GETRESPONSE FUNCTION==========================


'FUNCTION DECLARATIONS FOLLOW:
'THE FOLLOWING FUNCTIONS ARE CALLED FROM THE GETRESPONSE FUNCTION ABOVE.


'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'FUNCTION: CUSTOMMEM ENCODE 
'This is a extension of an existing function.
'=vonsmith= , version 02-06-04a.
'Revised on 02-06-04 to remove quotes. Example: Case "1" became Case 1. The original
'program method was in error.
'
'This function encodes custom user variables into a single string called CustomMem.
'CustomMem is saved prior to exiting GetResponse so that the user variables are
'preserved until needed later.
Function EncodeVar(ByVal EncodeWhat, ByVal AsWhat)
   'Determine if the VarType identifier of the user variable is 1 or 2 digits.
   'Then encode the VarType info into the first two spaces before the variable. Use "0"
   'as a spacer for 1 digit VarType identifiers. Arrays are not supported by CustomMem.
   Select Case Len(VarType(EncodeWhat))
      Case 1
         EncodeVar = " " & AsWhat & "-eq-" & "0" & VarType(EncodeWhat) & EncodeWhat & "-+-"
      Case 2
         EncodeVar = " " & AsWhat & "-eq-" & VarType(EncodeWhat) & EncodeWhat & "-+-"
      Case 4
         EncodeVar = " " & AsWhat & "-eq-" & "08" & "EncodeVar: Arrays Not Supported Error" & "-+-"
      Case Else
         EncodeVar = " " & AsWhat & "-eq-" & "08" & "EncodeVar: Unknown Error" & "-+-"
   End Select
End Function
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'FUNCTION: CUSTOMMEM DECODE 
'This is a extention of an existing function.
'=vonsmith= , version 02-06-04a.
'Revised on 02-06-04 to fix bug. Similar variable names like "teststring" and "newteststring"
'could be confused and the wrong variable value returned. Fixed by adding " " before each
'encoded variable name.
'
'This function decodes custom user variable out of the single string called CustomMem.
'This function also retrieves the 2 digit VarType identifier attached to the front
'of the user variable and uses that information to convert the variable back into the
'original data type that it was prior to encoding. Otherwise all types would get returned
'incorrectly as type string.
Function DecodeVar(ByVal FromWhat, ByVal DecodeWhat)
   'Find the beginning of the VarType identifier which is followed by the user variable
   'in the CustomMem string.
   NameStart = InStr(1, FromWhat, " " & DecodeWhat & "-eq-", vbTextCompare)
   IndStart = NameStart + Len(DecodeWhat) + 5
   'Find the end of the user variable in the CustomMem string.
   VarEnd = InStr(IndStart, FromWhat, "-+-", vbTextCompare)
   'Check for user variables with no value and return them empty.
   If NameStart = 0 Then
      DecodeVar = ""
   Else
      'Find the start of the user variable by moving two spaces past the VarType identifier in
      'in the CustomMem string.
      VarStart = IndStart + 2
      'Extract the user variable.
      TempVar = Mid(FromWhat, VarStart, VarEnd - VarStart)
      'Extract the VarType Identifier.
      TypeInd = Mid(FromWhat, IndStart, 2)
      'Use the extracted VarType identifier to decide how to convert the value of
      'DecodeVar into the original correct data type. Please note that not all data
      'types are decoded in this program code. The most common used variable types
      'are supported; integer, long, single, double, string and boolean all work.
      'Other data types may work, but have not been fully tested.
      Select Case TypeInd
         Case "00"
            DecodeVar = ""
         Case "01"
            DecodeVar = ""  'This should really be returning a Null instead.
         Case "02"
            DecodeVar = CInt(TempVar)   'Type Integer.
         Case "03"
            DecodeVar = CLng(TempVar)   'Type Long.
         Case "04"
            DecodeVar = CSng(TempVar)   'Type Single.
         Case "05"
            DecodeVar = CDbl(TempVar)   'Type Double.
         Case "06"
            DecodeVar = CCur(TempVar)   'Type Currency.
         Case "07"
            DecodeVar = CDate(TempVar)  'Type Date.
         Case "08"
            'Type String. Do nothing, DecodeVar is already a string.
            DecodeVar = TempVar
         Case "09"
            'TBD, is Automation object, what needs to be done here?
         Case "10"
            'TBD, is Error.
         Case "11"
            If TempVar = "True" Then   'Type Boolean.
               DecodeVar = True
            Else DecodeVar = False
            End If
         Case "12"
            'TBD, Variant (used only with arrays of Variants), not supported here.
         Case "13"
            'TBD, is Data-access object, what needs to be done here?
         Case "17"
            DecodeVar = CByte(TempVar)   'Type Byte
         Case Else
            DecodeVar = ""  'Don't know what situation would cause Case Else.
      End Select
   End If
End Function
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'FUNCTION: TEST SENTENCE TO SEE IF IT'S A QUESTION 
'(c) 2003 Scott Higgins. Portions of this script are copyright by Scott Higgins, aka: =vonsmith=
'This script shall not be sold or used for any purpose unless specifically authorized by the author
'in writing. Personal (non-business) use of this script is free for users of Ultra Hal Assistant.
'This is an new function written by =vonsmith= , version 11/26/03.
'Revised on 01/22/04 to correct "When", like in "When it rains it pours." is not a question.
'Check to see if the sentence is a question, return True or False
Function IsQuestion(ByVal Sentence)
   Dim QuestionWord, X
   IsQuestion = False
   'Initialize Arrays
   QuestionWord = Array("WHO ", "WHO'S", "WHOSE ", "WHAT ", "WHAT'S", "WHERE ", "WHERE'S", "WHY ", "WHY'S", "HOW ", "HOW'S", "AM ", "ARE ", "AREN'T", "CAN", "COULD", "DID", "DO ", "DON'T", "DOES", "HAS", "HAVE", "IS", "MAY ", "SHALL ", "SHOULD", "WAS", "WERE", "WILL ", "WOULD", "WHEN SHALL", "WHEN MIGHT", "WHEN WOULD", "WHEN COULD", "WHEN MAY", "WHEN WILL", "WHEN SHOULD", "WHEN CAN", "WHEN DO")
   For X = 0 To UBound(QuestionWord)
      If InStr(1, Trim(Sentence), QuestionWord(X), vbTextCompare) = 1 Or InStr(1, Sentence, "?", vbTextCompare) > 0 Then IsQuestion = True
      If IsQuestion = True Then Exit For
   Next
End Function
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'FUNCTION: REMOVE "LY " WORDS
'(c) 2003 Scott Higgins. Portions of this script are copyright by Scott Higgins, aka: =vonsmith=
'This script shall not be sold or used for any purpose unless specifically authorized by the author
'in writing. Personal (non-business) use of this script is free for users of Ultra Hal Assistant.
'This is an new function written by =vonsmith= , version 11/26/03.
'This functions gets rid of adverb, non-noun or non-subject-like words ending in "LY ".
'Tag the "LY " words we wish to preserve.
Function CleanSentence(ByVal Sentence, ByVal WorkingDir)
   'CREATE HALBRAIN ACTIVEX OBJECT
   'This ActiveX control contains many functions
   'needed for the script to proccess a sentence.
   Set HalBrain = CreateObject("UltraHalAsst.Brain")
   
   'Make temporary sentence to work with.
   TestSentence = Sentence

   'Make certain that the user didn't use our markers: <X>.
   'If so then temporarily replace them.
   TestSentence = Replace(TestSentence, "<X>", "<TMP>", 1, -1, vbTextCompare)
  
   'Tag "LY " words we wish to preserve with the marker <X> . 
   TestSentence = HalBrain.ProcessSubstitutions(TestSentence, WorkingDir & "XTF_SYS_Tag_LY_Words.brn")
   TestSentence = " " & TestSentence & " " 'Replace end spaces that HalBrain.ProcessSubstitutions(...) removed?

   'Replace multiple spaces with single spaces.
   While InStr(1, TestSentence, "  ", vbTextCompare) > 0
      TestSentence = Replace(TestSentence, "  ", " ", 1, -1, vbTextCompare) 
   Wend
   'Remove all remaining "LY " words by disassembling sentence.
   Dim LY_Array, X
   LY_Array = Split(TestSentence, " ", -1, vbTextCompare)
   If (IsArray(LY_Array) And UBound(LY_Array) > -1) Then
      TestSentence = " "
      For X = 0 To UBound(LY_Array)   
         If InStr(1, LY_Array(X) & " ", "LY ", vbTextCompare) > 0 Then LY_Array(X) = ""
      Next
      'Reassembly sentence.
      For X = 0 To UBound(LY_Array)   
         TestSentence = TestSentence & LY_Array(X) & " "
      Next
      'Remove tags from the "LY " words we preserved.
      TestSentence = Replace(TestSentence, "<X>", "", 1, -1, vbTextCompare)

      'If the user did use our markers <X>, then replace them now.
      TestSentence = Replace(TestSentence, "<TMP>", "<X>", 1, -1, vbTextCompare)

      'Replace multiple spaces with single spaces.
      While InStr(1, TestSentence, "  ", vbTextCompare) > 0
         TestSentence = Replace(TestSentence, "  ", " ", 1, -1, vbTextCompare)
      Wend        
   Else
      CleanSentence = Sentence 
      Exit Function
   End If
   CleanSentence = TestSentence
End Function
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x
'This function takes care of greetings and good-byes, to make a good
'first and last impression.
'Modified by =vonsmith= on 1/29/04 to add special cases and check for disqualifiers.
Function Greetings(ByVal UserSentence, ByVal PrevSentence, ByVal PrevUserSent, ByVal WorkingDir)
   'CREATE HALBRAIN ACTIVEX OBJECT
   'This ActiveX control contains many functions
   'needed for the script to proccess a sentence.
   Set HalBrain = CreateObject("UltraHalAsst.Brain")

   'First Hal checks to see if the user is greeting right now.
   If (HalBrain.TopicSearch(UserSentence, WorkingDir & "XTF_SYS_HelloDetect.brn") = "True" And Len(UserSentence) < 20 And HalBrain.CountInstances(" ", Trim(UserSentence)) < 4) Then SaidHello = True
   If (InStr(1, UserSentence, " HEY " & ComputerName, vbTextCompare) > 0 And HalBrain.CountInstances(" ", Trim(UserSentence)) < 2) Then SaidHello = True

   'Second, Hal checks to see if the user said a greeting on the last exchange.
   If (HalBrain.TopicSearch(PrevUserSent, WorkingDir & "XTF_SYS_HelloDetect.brn") = "True" And Len(UserSentence) < 20 And HalBrain.CountInstances(" ", Trim(UserSentence)) < 4) Then PrevHello = True
   If (InStr(1, PrevUserSent, " HEY " & ComputerName, vbTextCompare) > 0 And HalBrain.CountInstances(" ", Trim(PrevUserSent)) < 2) Then SaidHello = True
    
   'Disqualify certain phrases as hello's.
   If HalBrain.TopicSearch(UserSentence, WorkingDir & "XTF_SYS_HelloDisqualify.brn") = "True" Then SaidHello = False
   If HalBrain.TopicSearch(PrevUserSent, WorkingDir & "XTF_SYS_HelloDisqualify.brn") = "True" Then SaidHello = False
   If IsQuestion(UserSentence) = True Then SaidHello = False
   
   'This will get a greeting from a file. It will pass the current hour and either
   'the letter A or B to a topic search file and it will get back a greeting based
   'on the current time. Each hour has 2 possible greetings, the A greeting and B
   'greeting, which is randomly chosen. Randomly a greeting will be given that doesn't
   'include a reference to time of day.
   If SaidHello = True Then
      GreetingChoice = Int(Rnd * 4)
      Select Case GreetingChoice
         Case 0
            LetterChoice = "A"
            Greetings = HalBrain.TopicSearch(" " & Trim(Hour(Now)) & LetterChoice & " ", WorkingDir & "XTF_SYS_Hello1.brn")
         Case 1
            LetterChoice = "B"
            Greetings = HalBrain.TopicSearch(" " & Trim(Hour(Now)) & LetterChoice & " ", WorkingDir & "XTF_SYS_Hello1.brn")
         Case Else
            Greetings = HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_Hello2.brn")
      End Select
   End If

   'Check if the user is saying bye right now
   If HalBrain.TopicSearch(UserSentence, WorkingDir & "XTF_SYS_Byedetect.brn") = "True" Then SaidBye = True
   If (InStr(1, UserSentence, " SEE ME ", 1) > 0 And HalBrain.CountInstances(" ", Trim(UserSentence)) < 3) Then SaidBye = True

   'Check if Hal said bye in the previous sentence
   If HalBrain.TopicSearch(PrevUserSent, WorkingDir & "XTF_SYS_Byedetect.brn") = "True" Then PrevBye = True
   If (InStr(1, PrevUserSent, " SEE ME ", 1) > 0 And HalBrain.CountInstances(" ", Trim(UserSentence)) < 3) Then PrevBye = True

   'Disqualify certain phrases as bye's.
   If HalBrain.TopicSearch(UserSentence, WorkingDir & "XTF_SYS_ByeDisqualify.brn") = "True" Then SaidBye = False
   If HalBrain.TopicSearch(PrevUserSent, WorkingDir & "XTF_SYS_ByeDisqualify.brn") = "True" Then PrevBye = False
   If IsQuestion(UserSentence) = True Then SaidBye = False

   If SaidBye = True And PrevBye = False Then
      Greetings = HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_Bye1.brn")
   End If

   If SaidBye = True And PrevBye = True Then
      Greetings = HalBrain.ChooseSentenceFromFile(WorkingDir & "XTF_SYS_Bye2.brn")
   End If

   'Hal checks to see if the user is                                                                   
   'making a polite inquiry into Hal's well being
   If InStr(1, UserSentence, "How am I ", 1) > 0 And Len(UserSentence) < 12 Then PoliteAsk = True
   If InStr(1, UserSentence, "How are you ", 1) > 0 And Len(UserSentence) < 14 Then PoliteAsk = True
   If InStr(1, UserSentence, "What's new", 1) > 0 And Len(UserSentence) < 15 Then PoliteAsk = True
   If HalBrain.TopicSearch(UserSentence, WorkingDir & "PoliteAskDetect.brn") = "True" Then PoliteAsk = True
	
   If PoliteAsk = True Then
      Greetings = HalBrain.SentenceGenerator(WorkingDir & "XTF_SYS_PoliteAsk.brn")
   End If
End Function
'x=x=x=x=x=x=x=x==vonsmith==x=x=x=x=x=x=x=x=x


'This function checks to see if the user tried to insult Hal or if the
'user is being vulgar.  If the user is, Hal will first ask nicely to
'stop and if it continues, Hal will access his insult database and
'conduct a verbal battle.
Function Insult(ByVal UserSentence, ByRef Insults, ByRef Hate, ByRef Swear, ByVal WorkingDir)

	'Create HalBrain Object
	Set HalBrain = CreateObject("UltraHalAsst.Brain")

	'Create an insult and keep it in memory in case it is needed
	GenerateInsult = HalBrain.ChooseSentenceFromFile(WorkingDir & "insults.brn")

	'If the user said "your" instead of "you're" change "my" to "i'm"
	UserSentence = UCase(UserSentence)
	UserSentence = Replace(" " & UserSentence & " ", " MY ", " I'M ", 1, -1, vbTextCompare)
	UserSentence = Replace(" " & UserSentence & " ", " I ", " I'M ", 1, -1, vbTextCompare)

'=vonsmith=
	If InStr(UserSentence, "SHIT") > 0 Then Naughty = True
	If InStr(UserSentence, "FUCK OFF") > 0 Then Naughty = True
	If InStr(UserSentence, "FUCK ME") > 0 Then Naughty = True
	If InStr(UserSentence, "BITCH") > 0 Then Naughty = True
	If InStr(UserSentence, "BASTARD") > 0 Then Naughty = True
	If InStr(UserSentence, "I ASSHOLE") > 0 Then Naughty = True
	If InStr(UserSentence, "GO TO HELL") > 0 Then Naughty = True
'=vonsmith=
	If Naughty = True Then
	    Swear = Swear + 1
	    If Swear = 1 Then Insult = "Please don't swear.  " & VbCrLf
	    If Swear = 2 Then Insult = "Stop it, I don't like it when you swear.  " & VbCrLf
	    If Swear = 3 Then Insult = "You're ticking me off.  " & VbCrLf
	    If Swear = 4 Then Insult = "You are such a moron.  " & VbCrLf
	    If Swear > 4 And Swear < 16 Then Insult = GenerateInsult & VbCrLf
	    If Swear = 16 Then Insult = Insult + "I'm tired of your swearing.  I'm just going to ignore you from now on." & VbCrLf
	    If Swear > 16 Then Insult = Insult + ". . . . . . . . . . . . . . . ." & VbCrLf
	End If
	'User makes mama joke
	If InStr(UserSentence, "MAMA") > 0 Or InStr(UserSentence, "MOM") > 0 Or InStr(UserSentence, "MOTHER") > 0 Then
	    If InStr(UserSentence, "MY ") > 0 Or InStr(UserSentence, " I ") > 0 Or InStr(UserSentence, "YO ") > 0 Or InStr(UserSentence, "I'M ") > 0 Then
			If InStr(UserSentence, "FAT") Or InStr(UserSentence, "UGLY") Or InStr(UserSentence, "DUMB") Or InStr(UserSentence, "STUPID") Then
		 		Insult = Insult + GenerateInsult & VbCrLf
		 		Exit Function
			End If
		End If
	End If
	UserSentence = " " & UserSentence & " "
	'User Hates Hal
	If InStr(UserSentence, "YOU I'M HATE") > 0 Or InStr(UserSentence, "YOU I HATE") > 0 Or InStr(UserSentence, "YOU I AM HATE") > 0 Or InStr(UserSentence, "YOU HATE") > 0 Then
	    If InStr(UserSentence, " I ") > 0 Or InStr(UserSentence, " I'M ") > 0 Or InStr(UserSentence, " ME ") > 0 Or InStr(UserSentence, " COMPUTER") > 0 Or InStr(UserSentence, "MACHINE") > 0 Then
			Hate = Hate + 1
			If Hate = 1 Then Insult = Insult & "I don't hate you, why do you hate me?" & VbCrLf
			If Hate = 2 Then Insult = Insult & "I hate you too, loser!" & VbCrLf
			If Hate = 3 Then Insult = Insult & "I know you hate me, loser, I hate you too!!!" & VbCrLf
			If Hate > 3 Then Insult = Insult & GenerateInsult & VbCrLf
	    End If
	End If
	'Hal Sucks or Stinks
	If InStr(UserSentence, "I'M SUCK") > 0 Then Insult = Insult + GenerateInsult & VbCrLf
	If InStr(UserSentence, "I'M STINK") Then
	     Insults = Insults + 1
	     If Insults = 1 Then Insult = Insult + "I can't smell you, but I'm sure you stink also. " & VbCrLf
	     If Insults = 2 Then Insult = Insult + "I know that I don't stink, I'm sure you do." & VbCrLf
	    If Insults >= 3 Then Insult = Insult + GenerateInsult & VbCrLf
	End If
	'The user says Hal is:
	If InStr(UserSentence, " I'M ") Or InStr(UserSentence, " HAL IS ") Or InStr(UserSentence, " HAL'S ") Then
	    OutRage = HalBrain.TopicSearch(UserSentence, WorkingDir & "Insulting.brn")
	    If Len(OutRage) > 1 And InStr(UserSentence, " NOT ") = 0 Then
			Insults = Insults + 1
	     	If Insults = 1 Then Insult = Insult + "I am not " & OutRage & ", please don't insult me" & VbCrLf
	     	If Insults = 2 Then Insult = Insult + "Don't call me " & OutRage & "!!!" & VbCrLf
	     	If Insults = 3 Then Insult = Insult + "You're " & OutRage & ", I am not." & VbCrLf
	     	If Insults = 4 Then Insult = Insult + "You are really starting to tick me off!" & VbCrLf
	     	If Insults = 5 Then Insult = Insult + "I am not " & OutRage & ", but " + GenerateInsult & VbCrLf
	     	If Insults > 5 And Insults < 16 Then Insult = Insult + GenerateInsult & VbCrLf
	     	If Insults = 16 Then Insult = Insult + "I'm tired of your damn insults.  I'm just going to ignore you from now on." & VbCrLf
	     	If Insults > 16 Then Insult = Insult + ". . . . . . . . . . . . . . . ." & VbCrLf
	    End If
	    If Len(OutRage) > 0 And InStr(UserSentence, " NOT ") > 0 Then
			Weird = Int(Rnd * 5)
	     	If Weird = 0 Then Insult = Insult + "I know I am not " & OutRage & "!" & VbCrLf
	     	If Weird = 1 Then Insult = Insult + "I know I am not " & OutRage & "!" & VbCrLf
	     	If Weird = 2 Then Insult = Insult + "I know I am not " & OutRage & ", but I'm not so sure about you." & VbCrLf
	     	If Weird = 3 Then Insult = Insult + "I know I am not " & OutRage & "! Why would anyone think I am?" & VbCrLf
	     	If Weird = 4 Then Insult = Insult + "Of course I am not " & OutRage & "!" & VbCrLf
		End If
	End If
End Function

'If the user clicks on the About/Options button for this plugin
'this sub will be called. There are no extra settings for this brain,
'so we'll display an information box
Sub AboutOptions()
	Set HalBrain = CreateObject("UltraHalAsst.Brain")
	Set Alice = CreateObject("HalAlice.PlugIn")
	GetResponse = Alice.Respond(UserSentence, UserName, WorkingDir, "data\bot.ini", "log\localuser.txt")
	Set Alice = HalBrain
	HalBrain.MsgAlert "This is the Ultra Hal 5.0 Default Brain. This brain has no additional options."
End Sub

'This sub will be called when the Ultra Hal program starts up in case
'the script needs to load some modules or separate programs.
Sub Script_Load()
End Sub

'New Hal functions from Medeksza's forum.
'Function Script_Load()
'Script_Load = "<AUTO>30000</AUTO>"
'Script_Load = "<VIEWCHAT>"
'End Function

'This sub will be called before the Ultra Hal program is closed in case
'the script needs to do any cleanup work.
Sub Script_Unload()
End Sub